generated from substrate-developer-hub/substrate-node-template
-
Notifications
You must be signed in to change notification settings - Fork 60
/
lib.rs
903 lines (771 loc) · 29.2 KB
/
lib.rs
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
// This file is part of pallet-route-executor.
// Copyright (C) 2020-2022 Intergalactic, Limited (GIB).
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::MaxEncodedLen;
use frame_support::storage::with_transaction;
use frame_support::traits::fungibles::Mutate;
use frame_support::traits::tokens::{Fortitude, Preservation};
use frame_support::PalletId;
use frame_support::{
ensure,
pallet_prelude::*,
traits::{fungibles::Inspect, Get},
transactional,
};
use hydra_dx_math::support::rational::{round_u512_to_rational, Rounding};
use frame_system::pallet_prelude::OriginFor;
use frame_system::{ensure_signed, Origin};
use hydradx_traits::registry::Inspect as RegistryInspect;
use hydradx_traits::router::{inverse_route, AssetPair, RefundEdCalculator, RouteProvider, RouteSpotPriceProvider};
pub use hydradx_traits::router::{
AmmTradeWeights, AmountInAndOut, ExecutorError, PoolType, RouterT, Trade, TradeExecution,
};
use orml_traits::arithmetic::{CheckedAdd, CheckedSub};
use sp_core::U512;
use sp_runtime::traits::{AccountIdConversion, CheckedDiv};
use sp_runtime::{ArithmeticError, DispatchError, FixedPointNumber, FixedU128, Saturating, TransactionOutcome};
use sp_std::{vec, vec::Vec};
#[cfg(test)]
mod tests;
pub mod weights;
// Re-export pallet items so that they can be accessed from the crate namespace.
pub use pallet::*;
pub const MAX_NUMBER_OF_TRADES: u32 = 5;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::traits::fungibles::Mutate;
use frame_system::pallet_prelude::OriginFor;
use hydradx_traits::router::{ExecutorError, RefundEdCalculator};
use sp_runtime::traits::{AtLeast32BitUnsigned, CheckedDiv, Zero};
use sp_runtime::Saturating;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Asset id type
type AssetId: Parameter + Member + Copy + MaybeSerializeDeserialize + MaxEncodedLen + AtLeast32BitUnsigned;
/// Balance type
type Balance: Parameter
+ Member
+ Copy
+ PartialOrd
+ MaybeSerializeDeserialize
+ From<u128>
+ Default
+ CheckedSub
+ CheckedAdd
+ CheckedDiv
+ Saturating
+ Zero;
/// Native Asset Id
#[pallet::constant]
type NativeAssetId: Get<Self::AssetId>;
/// Currency for checking balances and temporarily minting tokens
type Currency: Inspect<Self::AccountId, AssetId = Self::AssetId, Balance = Self::Balance>
+ Mutate<Self::AccountId>;
type InspectRegistry: hydradx_traits::registry::Inspect<AssetId = Self::AssetId>;
/// Handlers for AMM pools to calculate and execute trades
type AMM: TradeExecution<
<Self as frame_system::Config>::RuntimeOrigin,
Self::AccountId,
Self::AssetId,
Self::Balance,
Error = DispatchError,
>;
type EdToRefundCalculator: RefundEdCalculator<Self::Balance>;
/// Pool type used in the default route
type DefaultRoutePoolType: Get<PoolType<Self::AssetId>>;
/// Origin able to set route without validation
type TechnicalOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Weight information for the extrinsics.
type WeightInfo: AmmTradeWeights<Trade<Self::AssetId>>;
}
#[pallet::event]
#[pallet::generate_deposit(pub(crate) fn deposit_event)]
pub enum Event<T: Config> {
///The route with trades has been successfully executed
Executed {
asset_in: T::AssetId,
asset_out: T::AssetId,
amount_in: T::Balance,
amount_out: T::Balance,
},
///The route with trades has been successfully executed
RouteUpdated { asset_ids: Vec<T::AssetId> },
}
#[pallet::error]
pub enum Error<T> {
///The trading limit has been reached
TradingLimitReached,
///The the max number of trades limit is reached
MaxTradesExceeded,
///The AMM pool is not supported for executing trades
PoolNotSupported,
///The user has not enough balance to execute the trade
InsufficientBalance,
///The calculation of route trade amounts failed in the underlying AMM
RouteCalculationFailed,
///The route is invalid
InvalidRoute,
///The route update was not successful
RouteUpdateIsNotSuccessful,
///Insufficient asset is not supported for on chain routing
InsufficientAssetNotSupported,
///The route execution failed in the underlying AMM
InvalidRouteExecution,
/// Trading same assets is not allowed.
NotAllowed,
}
/// Storing routes for asset pairs
#[pallet::storage]
#[pallet::getter(fn route)]
pub type Routes<T: Config> = StorageMap<
_,
Blake2_128Concat,
AssetPair<T::AssetId>,
BoundedVec<Trade<T::AssetId>, ConstU32<MAX_NUMBER_OF_TRADES>>,
>;
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Executes a sell with a series of trades specified in the route.
/// The price for each trade is determined by the corresponding AMM.
///
/// - `origin`: The executor of the trade
/// - `asset_in`: The identifier of the asset to sell
/// - `asset_out`: The identifier of the asset to receive
/// - `amount_in`: The amount of `asset_in` to sell
/// - `min_amount_out`: The minimum amount of `asset_out` to receive.
/// - `route`: Series of [`Trade<AssetId>`] to be executed. A [`Trade<AssetId>`] specifies the asset pair (`asset_in`, `asset_out`) and the AMM (`pool`) in which the trade is executed.
/// If not specified, than the on-chain route is used.
/// If no on-chain is present, then omnipool route is used as default
///
/// Emits `RouteExecuted` when successful.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::sell_weight(route))]
#[transactional]
pub fn sell(
origin: OriginFor<T>,
asset_in: T::AssetId,
asset_out: T::AssetId,
amount_in: T::Balance,
min_amount_out: T::Balance,
route: Vec<Trade<T::AssetId>>,
) -> DispatchResult {
let who = ensure_signed(origin.clone())?;
ensure!(asset_in != asset_out, Error::<T>::NotAllowed);
Self::ensure_route_size(route.len())?;
let asset_pair = AssetPair::new(asset_in, asset_out);
let route = Self::get_route_or_default(route, asset_pair)?;
Self::ensure_route_arguments(&asset_pair, &route)?;
let user_balance_of_asset_out_before_trade =
T::Currency::reducible_balance(asset_out, &who, Preservation::Preserve, Fortitude::Polite);
let trade_amounts = Self::calculate_sell_trade_amounts(&route, amount_in)?;
let last_trade_amount = trade_amounts.last().ok_or(Error::<T>::RouteCalculationFailed)?;
ensure!(
last_trade_amount.amount_out >= min_amount_out,
Error::<T>::TradingLimitReached
);
for (trade_amount, trade) in trade_amounts.iter().zip(route) {
let user_balance_of_asset_in_before_trade =
T::Currency::reducible_balance(trade.asset_in, &who, Preservation::Expendable, Fortitude::Polite);
let execution_result = T::AMM::execute_sell(
origin.clone(),
trade.pool,
trade.asset_in,
trade.asset_out,
trade_amount.amount_in,
trade_amount.amount_out,
);
handle_execution_error!(execution_result);
Self::ensure_that_user_spent_asset_in_at_least(
who.clone(),
trade.asset_in,
user_balance_of_asset_in_before_trade,
trade_amount.amount_in,
)?;
}
Self::ensure_that_user_received_asset_out_at_most(
who,
asset_in,
asset_out,
user_balance_of_asset_out_before_trade,
last_trade_amount.amount_out,
)?;
Self::deposit_event(Event::Executed {
asset_in,
asset_out,
amount_in,
amount_out: last_trade_amount.amount_out,
});
Ok(())
}
/// Executes a buy with a series of trades specified in the route.
/// The price for each trade is determined by the corresponding AMM.
///
/// - `origin`: The executor of the trade
/// - `asset_in`: The identifier of the asset to be swapped to buy `asset_out`
/// - `asset_out`: The identifier of the asset to buy
/// - `amount_out`: The amount of `asset_out` to buy
/// - `max_amount_in`: The max amount of `asset_in` to spend on the buy.
/// - `route`: Series of [`Trade<AssetId>`] to be executed. A [`Trade<AssetId>`] specifies the asset pair (`asset_in`, `asset_out`) and the AMM (`pool`) in which the trade is executed.
/// If not specified, than the on-chain route is used.
/// If no on-chain is present, then omnipool route is used as default
///
/// Emits `RouteExecuted` when successful.
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::buy_weight(route))]
#[transactional]
pub fn buy(
origin: OriginFor<T>,
asset_in: T::AssetId,
asset_out: T::AssetId,
amount_out: T::Balance,
max_amount_in: T::Balance,
route: Vec<Trade<T::AssetId>>,
) -> DispatchResult {
let who = ensure_signed(origin.clone())?;
ensure!(asset_in != asset_out, Error::<T>::NotAllowed);
Self::ensure_route_size(route.len())?;
let asset_pair = AssetPair::new(asset_in, asset_out);
let route = Self::get_route_or_default(route, asset_pair)?;
Self::ensure_route_arguments(&asset_pair, &route)?;
let user_balance_of_asset_in_before_trade =
T::Currency::reducible_balance(asset_in, &who, Preservation::Expendable, Fortitude::Polite);
let trade_amounts = Self::calculate_buy_trade_amounts(&route, amount_out)?;
let first_trade = trade_amounts.last().ok_or(Error::<T>::RouteCalculationFailed)?;
ensure!(first_trade.amount_in <= max_amount_in, Error::<T>::TradingLimitReached);
for (trade_amount, trade) in trade_amounts.iter().rev().zip(route) {
let user_balance_of_asset_out_before_trade =
T::Currency::reducible_balance(trade.asset_out, &who, Preservation::Preserve, Fortitude::Polite);
let execution_result = T::AMM::execute_buy(
origin.clone(),
trade.pool,
trade.asset_in,
trade.asset_out,
trade_amount.amount_out,
trade_amount.amount_in,
);
handle_execution_error!(execution_result);
Self::ensure_that_user_received_asset_out_at_most(
who.clone(),
trade.asset_in,
trade.asset_out,
user_balance_of_asset_out_before_trade,
trade_amount.amount_out,
)?;
}
Self::ensure_that_user_spent_asset_in_at_least(
who,
asset_in,
user_balance_of_asset_in_before_trade,
first_trade.amount_in,
)?;
Self::deposit_event(Event::Executed {
asset_in,
asset_out,
amount_in: first_trade.amount_in,
amount_out,
});
Ok(())
}
/// Sets the on-chain route for a given asset pair.
///
/// The new route is validated by being executed in a dry-run mode
///
/// If there is no route explicitly set for an asset pair, then we use the omnipool route as default.
///
/// When a new route is set, we compare it to the existing (or default) route.
/// The comparison happens by calculating sell amount_outs for the routes, but also for the inversed routes.
///
/// The route is stored in an ordered manner, based on the oder of the ids in the asset pair.
///
/// If the route is set successfully, then the fee is payed back.
///
/// - `origin`: The origin of the route setter
/// - `asset_pair`: The identifier of the asset-pair for which the route is set
/// - `new_route`: Series of [`Trade<AssetId>`] to be executed. A [`Trade<AssetId>`] specifies the asset pair (`asset_in`, `asset_out`) and the AMM (`pool`) in which the trade is executed.
///
/// Emits `RouteUpdated` when successful.
///
/// Fails with `RouteUpdateIsNotSuccessful` error when failed to set the route
///
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::set_route_weight(new_route))]
#[transactional]
pub fn set_route(
origin: OriginFor<T>,
mut asset_pair: AssetPair<T::AssetId>,
mut new_route: Vec<Trade<T::AssetId>>,
) -> DispatchResultWithPostInfo {
let _ = ensure_signed(origin.clone())?;
Self::ensure_route_size(new_route.len())?;
Self::ensure_route_arguments(&asset_pair, &new_route)?;
Self::ensure_route_has_no_insufficient_asset(&new_route)?;
if !asset_pair.is_ordered() {
asset_pair = asset_pair.ordered_pair();
new_route = inverse_route(new_route)
}
let existing_route = Self::get_route(asset_pair);
match Self::validate_route(&existing_route) {
Ok((reference_amount_in, reference_amount_in_for_inverse)) => {
let new_route_validation = Self::validate_sell(new_route.clone(), reference_amount_in);
let inverse_new_route = inverse_route(new_route.to_vec());
let inverse_new_route_validation =
Self::validate_sell(inverse_new_route.clone(), reference_amount_in_for_inverse);
match (new_route_validation, inverse_new_route_validation) {
(Ok(_), Ok(_)) => (),
(Err(_), Ok(amount_out)) => {
Self::validate_sell(new_route.to_vec(), amount_out).map(|_| ())?;
}
(Ok(amount_out), Err(_)) => {
Self::validate_sell(inverse_new_route.clone(), amount_out).map(|_| ())?;
}
(Err(err), Err(_)) => return Err(err.into()),
}
let amount_out_for_existing_route =
Self::calculate_expected_amount_out(&existing_route, reference_amount_in)?;
let amount_out_for_new_route =
Self::calculate_expected_amount_out(&new_route, reference_amount_in)?;
let inverse_existing_route = inverse_route(existing_route.to_vec());
let amount_out_for_existing_inversed_route =
Self::calculate_expected_amount_out(&inverse_existing_route, reference_amount_in_for_inverse)?;
let amount_out_for_new_inversed_route =
Self::calculate_expected_amount_out(&inverse_new_route, reference_amount_in_for_inverse)?;
if amount_out_for_new_route > amount_out_for_existing_route
&& amount_out_for_new_inversed_route > amount_out_for_existing_inversed_route
{
return Self::insert_route(asset_pair, new_route);
}
}
Err(_) => {
Self::validate_route(&new_route)?;
return Self::insert_route(asset_pair, new_route);
}
}
Err(Error::<T>::RouteUpdateIsNotSuccessful.into())
}
/// Force inserts the on-chain route for a given asset pair, so there is no any validation for the route
///
/// Can only be called by technical origin
///
/// The route is stored in an ordered manner, based on the oder of the ids in the asset pair.
///
/// If the route is set successfully, then the fee is payed back.
///
/// - `origin`: The origin of the route setter
/// - `asset_pair`: The identifier of the asset-pair for which the route is set
/// - `new_route`: Series of [`Trade<AssetId>`] to be executed. A [`Trade<AssetId>`] specifies the asset pair (`asset_in`, `asset_out`) and the AMM (`pool`) in which the trade is executed.
///
/// Emits `RouteUpdated` when successful.
///
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::force_insert_route_weight())]
#[transactional]
pub fn force_insert_route(
origin: OriginFor<T>,
mut asset_pair: AssetPair<T::AssetId>,
mut new_route: Vec<Trade<T::AssetId>>,
) -> DispatchResultWithPostInfo {
T::TechnicalOrigin::ensure_origin(origin)?;
if !asset_pair.is_ordered() {
asset_pair = asset_pair.ordered_pair();
new_route = inverse_route(new_route)
}
Self::insert_route(asset_pair, new_route)
}
}
}
impl<T: Config> Pallet<T> {
/// Pallet account address for do dry-run sell execution as validation
pub fn router_account() -> T::AccountId {
PalletId(*b"routerex").into_account_truncating()
}
fn ensure_route_size(route_length: usize) -> Result<(), DispatchError> {
ensure!(
(route_length as u32) <= MAX_NUMBER_OF_TRADES,
Error::<T>::MaxTradesExceeded
);
Ok(())
}
fn ensure_route_arguments(
asset_pair: &AssetPair<T::AssetId>,
route: &[Trade<T::AssetId>],
) -> Result<(), DispatchError> {
ensure!(
asset_pair.asset_in == route.first().ok_or(Error::<T>::InvalidRoute)?.asset_in,
Error::<T>::InvalidRoute
);
ensure!(
asset_pair.asset_out == route.last().ok_or(Error::<T>::InvalidRoute)?.asset_out,
Error::<T>::InvalidRoute
);
for i in 0..route.len().saturating_sub(1) {
let asset_out = route.get(i).ok_or(Error::<T>::InvalidRoute)?.asset_out;
let next_trade_asset_in = route.get(i.saturating_add(1)).ok_or(Error::<T>::InvalidRoute)?.asset_in;
ensure!(asset_out == next_trade_asset_in, Error::<T>::InvalidRoute)
}
Ok(())
}
fn ensure_route_has_no_insufficient_asset(new_route: &[Trade<T::AssetId>]) -> DispatchResult {
let mut unique_assets = sp_std::collections::btree_set::BTreeSet::new();
for trade in new_route.iter() {
unique_assets.insert(trade.asset_in);
unique_assets.insert(trade.asset_out);
}
for asset in unique_assets.iter() {
ensure!(
T::InspectRegistry::is_sufficient(*asset),
Error::<T>::InsufficientAssetNotSupported
);
}
Ok(())
}
fn ensure_that_user_received_asset_out_at_most(
who: T::AccountId,
asset_in: T::AssetId,
asset_out: T::AssetId,
user_balance_of_asset_out_before_trade: T::Balance,
expected_received_amount: T::Balance,
) -> Result<(), DispatchError> {
let user_balance_of_asset_out_after_trade =
T::Currency::reducible_balance(asset_out, &who, Preservation::Preserve, Fortitude::Polite);
let actual_received_amount = user_balance_of_asset_out_after_trade
.checked_sub(&user_balance_of_asset_out_before_trade)
.ok_or(Error::<T>::InvalidRouteExecution)?;
if !T::InspectRegistry::is_sufficient(asset_in) && asset_out == T::NativeAssetId::get() {
// In case of selling all insufficient asset, ED in HDX is refund to user, so end-balance will be more with ED
// In this case we check if the user does not receive more than ED
let diff = actual_received_amount.saturating_sub(expected_received_amount);
let ed_to_refund = T::EdToRefundCalculator::calculate();
ensure!(diff <= ed_to_refund, Error::<T>::InvalidRouteExecution);
} else {
ensure!(
actual_received_amount <= expected_received_amount,
Error::<T>::InvalidRouteExecution
);
}
Ok(())
}
fn ensure_that_user_spent_asset_in_at_least(
who: T::AccountId,
asset_in: T::AssetId,
user_balance_of_asset_in_before_trade: T::Balance,
expected_spent_amount: T::Balance,
) -> Result<(), DispatchError> {
let user_balance_of_asset_in_after_trade =
T::Currency::reducible_balance(asset_in, &who, Preservation::Preserve, Fortitude::Polite);
let actual_spent_amount = user_balance_of_asset_in_before_trade
.checked_sub(&user_balance_of_asset_in_after_trade)
.ok_or(Error::<T>::InvalidRouteExecution)?;
ensure!(
actual_spent_amount >= expected_spent_amount,
Error::<T>::InvalidRouteExecution
);
Ok(())
}
fn get_route_or_default(
route: Vec<Trade<T::AssetId>>,
asset_pair: AssetPair<T::AssetId>,
) -> Result<Vec<Trade<T::AssetId>>, DispatchError> {
let route = if !route.is_empty() {
route
} else {
<Pallet<T> as RouteProvider<T::AssetId>>::get_route(asset_pair)
};
Ok(route)
}
fn validate_route(route: &[Trade<T::AssetId>]) -> Result<(T::Balance, T::Balance), DispatchError> {
let reference_amount_in = Self::calculate_reference_amount_in(route)?;
let route_validation = Self::validate_sell(route.to_vec(), reference_amount_in);
let inverse_route = inverse_route(route.to_vec());
let reference_amount_in_for_inverse_route = Self::calculate_reference_amount_in(&inverse_route)?;
let inverse_route_validation =
Self::validate_sell(inverse_route.clone(), reference_amount_in_for_inverse_route);
match (route_validation, inverse_route_validation) {
(Ok(_), Ok(_)) => Ok((reference_amount_in, reference_amount_in_for_inverse_route)),
(Err(_), Ok(amount_out)) => Self::validate_sell(route.to_vec(), amount_out)
.map(|_| (amount_out, reference_amount_in_for_inverse_route)),
(Ok(amount_out), Err(_)) => {
Self::validate_sell(inverse_route, amount_out).map(|_| (reference_amount_in, amount_out))
}
(Err(err), Err(_)) => Err(err),
}
}
fn calculate_reference_amount_in(route: &[Trade<T::AssetId>]) -> Result<T::Balance, DispatchError> {
let first_route = route.first().ok_or(Error::<T>::RouteCalculationFailed)?;
let asset_b = match first_route.pool {
PoolType::Omnipool => T::NativeAssetId::get(),
PoolType::Stableswap(pool_id) => pool_id,
PoolType::XYK => first_route.asset_out,
PoolType::LBP => first_route.asset_out,
};
let asset_in_liquidity = T::AMM::get_liquidity_depth(first_route.pool, first_route.asset_in, asset_b);
let liquidity = match asset_in_liquidity {
Err(ExecutorError::NotSupported) => return Err(Error::<T>::PoolNotSupported.into()),
Err(ExecutorError::Error(dispatch_error)) => return Err(dispatch_error),
Ok(liq) => liq,
};
let one_percent_asset_in_liquidity = liquidity
.checked_div(&100u128.into())
.ok_or(ArithmeticError::Overflow)?;
Ok(one_percent_asset_in_liquidity)
}
fn validate_sell(route: Vec<Trade<T::AssetId>>, amount_in: T::Balance) -> Result<T::Balance, DispatchError> {
let asset_in = route.first().ok_or(Error::<T>::InvalidRoute)?.asset_in;
let asset_out = route.last().ok_or(Error::<T>::InvalidRoute)?.asset_out;
with_transaction::<T::Balance, DispatchError, _>(|| {
let origin: OriginFor<T> = Origin::<T>::Signed(Self::router_account()).into();
let Ok(who) = ensure_signed(origin.clone()) else {
return TransactionOutcome::Rollback(Err(Error::<T>::InvalidRoute.into()));
};
let _ = T::Currency::mint_into(asset_in, &Self::router_account(), amount_in);
let sell_result = Self::sell(origin, asset_in, asset_out, amount_in, u128::MIN.into(), route.clone());
let amount_out =
T::Currency::reducible_balance(asset_out, &who, Preservation::Expendable, Fortitude::Polite);
TransactionOutcome::Rollback(sell_result.map(|_| amount_out))
})
}
fn calculate_expected_amount_out(
route: &[Trade<<T as Config>::AssetId>],
amount_in: T::Balance,
) -> Result<T::Balance, DispatchError> {
let sell_trade_amounts = Self::calculate_sell_trade_amounts(route, amount_in)?;
let amount_out = sell_trade_amounts
.last()
.ok_or(Error::<T>::RouteCalculationFailed)?
.amount_out;
Ok(amount_out)
}
fn calculate_sell_trade_amounts(
route: &[Trade<T::AssetId>],
amount_in: T::Balance,
) -> Result<Vec<AmountInAndOut<T::Balance>>, DispatchError> {
let mut amount_in_and_outs = Vec::<AmountInAndOut<T::Balance>>::with_capacity(route.len());
let mut amount_in = amount_in;
for trade in route.iter() {
let result = T::AMM::calculate_sell(trade.pool, trade.asset_in, trade.asset_out, amount_in);
match result {
Err(ExecutorError::NotSupported) => return Err(Error::<T>::PoolNotSupported.into()),
Err(ExecutorError::Error(dispatch_error)) => return Err(dispatch_error),
Ok(amount_out) => {
amount_in_and_outs.push(AmountInAndOut { amount_in, amount_out });
amount_in = amount_out;
}
}
}
Ok(amount_in_and_outs)
}
fn calculate_buy_trade_amounts(
route: &[Trade<T::AssetId>],
amount_out: T::Balance,
) -> Result<Vec<AmountInAndOut<T::Balance>>, DispatchError> {
let mut amount_in_and_outs = Vec::<AmountInAndOut<T::Balance>>::with_capacity(route.len());
let mut amount_out = amount_out;
for trade in route.iter().rev() {
let result = T::AMM::calculate_buy(trade.pool, trade.asset_in, trade.asset_out, amount_out);
match result {
Err(ExecutorError::NotSupported) => return Err(Error::<T>::PoolNotSupported.into()),
Err(ExecutorError::Error(dispatch_error)) => return Err(dispatch_error),
Ok(amount_in) => {
amount_in_and_outs.push(AmountInAndOut { amount_in, amount_out });
amount_out = amount_in;
}
}
}
Ok(amount_in_and_outs)
}
fn insert_route(asset_pair: AssetPair<T::AssetId>, route: Vec<Trade<T::AssetId>>) -> DispatchResultWithPostInfo {
let route_as_bounded_vec: BoundedVec<Trade<T::AssetId>, sp_runtime::traits::ConstU32<MAX_NUMBER_OF_TRADES>> =
route.try_into().map_err(|_| Error::<T>::MaxTradesExceeded)?;
Routes::<T>::insert(asset_pair, route_as_bounded_vec);
Self::deposit_event(Event::RouteUpdated {
asset_ids: asset_pair.to_ordered_vec(),
});
Ok(Pays::No.into())
}
}
impl<T: Config> RouterT<T::RuntimeOrigin, T::AssetId, T::Balance, Trade<T::AssetId>, AmountInAndOut<T::Balance>>
for Pallet<T>
{
fn sell(
origin: T::RuntimeOrigin,
asset_in: T::AssetId,
asset_out: T::AssetId,
amount_in: T::Balance,
min_amount_out: T::Balance,
route: Vec<Trade<T::AssetId>>,
) -> DispatchResult {
Pallet::<T>::sell(origin, asset_in, asset_out, amount_in, min_amount_out, route)
}
fn buy(
origin: T::RuntimeOrigin,
asset_in: T::AssetId,
asset_out: T::AssetId,
amount_out: T::Balance,
max_amount_in: T::Balance,
route: Vec<Trade<T::AssetId>>,
) -> DispatchResult {
Pallet::<T>::buy(origin, asset_in, asset_out, amount_out, max_amount_in, route)
}
fn calculate_sell_trade_amounts(
route: &[Trade<T::AssetId>],
amount_in: T::Balance,
) -> Result<Vec<AmountInAndOut<T::Balance>>, DispatchError> {
Pallet::<T>::calculate_sell_trade_amounts(route, amount_in)
}
fn calculate_buy_trade_amounts(
route: &[Trade<T::AssetId>],
amount_out: T::Balance,
) -> Result<Vec<AmountInAndOut<T::Balance>>, DispatchError> {
Pallet::<T>::calculate_buy_trade_amounts(route, amount_out)
}
fn set_route(
origin: T::RuntimeOrigin,
asset_pair: AssetPair<T::AssetId>,
route: Vec<Trade<T::AssetId>>,
) -> DispatchResultWithPostInfo {
Pallet::<T>::set_route(origin, asset_pair, route)
}
fn force_insert_route(
origin: T::RuntimeOrigin,
asset_pair: AssetPair<T::AssetId>,
route: Vec<Trade<T::AssetId>>,
) -> DispatchResultWithPostInfo {
Pallet::<T>::force_insert_route(origin, asset_pair, route)
}
}
pub struct DummyRouter<T>(PhantomData<T>);
impl<T: Config> RouterT<T::RuntimeOrigin, T::AssetId, T::Balance, Trade<T::AssetId>, AmountInAndOut<T::Balance>>
for DummyRouter<T>
{
fn sell(
_origin: T::RuntimeOrigin,
_asset_in: T::AssetId,
_asset_out: T::AssetId,
_amount_in: T::Balance,
_min_amount_out: T::Balance,
_route: Vec<Trade<T::AssetId>>,
) -> DispatchResult {
Ok(())
}
fn buy(
_origin: T::RuntimeOrigin,
_asset_in: T::AssetId,
_asset_out: T::AssetId,
_amount_out: T::Balance,
_max_amount_in: T::Balance,
_route: Vec<Trade<T::AssetId>>,
) -> DispatchResult {
Ok(())
}
fn calculate_sell_trade_amounts(
_route: &[Trade<T::AssetId>],
amount_in: T::Balance,
) -> Result<Vec<AmountInAndOut<T::Balance>>, DispatchError> {
Ok(vec![AmountInAndOut::<T::Balance> {
amount_in,
amount_out: amount_in,
}])
}
fn calculate_buy_trade_amounts(
_route: &[Trade<T::AssetId>],
amount_out: T::Balance,
) -> Result<Vec<AmountInAndOut<T::Balance>>, DispatchError> {
Ok(vec![AmountInAndOut::<T::Balance> {
amount_in: amount_out,
amount_out,
}])
}
fn set_route(
_origin: T::RuntimeOrigin,
_asset_pair: AssetPair<T::AssetId>,
_route: Vec<Trade<T::AssetId>>,
) -> DispatchResultWithPostInfo {
Ok(Pays::Yes.into())
}
fn force_insert_route(
_origin: T::RuntimeOrigin,
_asset_pair: AssetPair<T::AssetId>,
_route: Vec<Trade<T::AssetId>>,
) -> DispatchResultWithPostInfo {
Ok(Pays::Yes.into())
}
}
#[macro_export]
macro_rules! handle_execution_error {
($execution_result:expr) => {{
if let Err(error) = $execution_result {
return match error {
ExecutorError::NotSupported => Err(Error::<T>::PoolNotSupported.into()),
ExecutorError::Error(dispatch_error) => Err(dispatch_error),
};
}
}};
}
impl<T: Config> RouteProvider<T::AssetId> for Pallet<T> {
fn get_route(asset_pair: AssetPair<T::AssetId>) -> Vec<Trade<T::AssetId>> {
let onchain_route = Routes::<T>::get(asset_pair.ordered_pair());
let default_route = vec![Trade {
pool: T::DefaultRoutePoolType::get(),
asset_in: asset_pair.asset_in,
asset_out: asset_pair.asset_out,
}];
match onchain_route {
Some(route) => {
if asset_pair.is_ordered() {
route.to_vec()
} else {
inverse_route(route.to_vec())
}
}
None => default_route,
}
}
}
impl<T: Config> RouteSpotPriceProvider<T::AssetId> for Pallet<T> {
fn spot_price_with_fee(route: &[Trade<T::AssetId>]) -> Option<FixedU128> {
if route.is_empty() {
return None;
}
let mut nominator = U512::from(1u128);
let mut denominator = U512::from(1u128);
// We aggregate the prices after every 4 hops to prevent overflow of U512
for chunk_with_4_hops in route.chunks(4) {
let mut prices: Vec<FixedU128> = Vec::with_capacity(chunk_with_4_hops.len());
for trade in chunk_with_4_hops {
let spot_price_result =
T::AMM::calculate_spot_price_with_fee(trade.pool, trade.asset_in, trade.asset_out);
match spot_price_result {
Ok(spot_price) => prices.push(spot_price),
Err(_) => return None,
}
}
// Calculate the nominator and denominator for the current chunk
let chunk_nominator = prices.iter().try_fold(U512::from(1u128), |acc, price| {
acc.checked_mul(U512::from(price.into_inner()))
})?;
let chunk_denominator = prices.iter().try_fold(U512::from(1u128), |acc, _price| {
acc.checked_mul(U512::from(FixedU128::DIV))
})?;
// Combine the chunk results with the final results
nominator = nominator.checked_mul(chunk_nominator)?;
denominator = denominator.checked_mul(chunk_denominator)?;
}
let rat_as_u128 = round_u512_to_rational((nominator, denominator), Rounding::Nearest);
FixedU128::checked_from_rational(rat_as_u128.0, rat_as_u128.1)
}
}