-
Notifications
You must be signed in to change notification settings - Fork 103
/
contract.rs
1306 lines (1159 loc) · 44.8 KB
/
contract.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
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
use std::collections::HashMap;
use std::str::FromStr;
use std::vec;
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
attr, from_json, to_json_binary, wasm_execute, wasm_instantiate, Addr, Binary, CosmosMsg,
Decimal, Decimal256, Deps, DepsMut, Env, Fraction, MessageInfo, QuerierWrapper, Reply,
Response, StdError, StdResult, SubMsg, SubMsgResponse, SubMsgResult, Uint128, WasmMsg,
};
use cw2::{get_contract_version, set_contract_version};
use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg, MinterResponse};
use cw_utils::parse_instantiate_response_data;
use itertools::Itertools;
use astroport::asset::{
addr_opt_validate, check_swap_parameters, format_lp_token_name, Asset, AssetInfo, CoinsExt,
Decimal256Ext, DecimalAsset, PairInfo, MINIMUM_LIQUIDITY_AMOUNT,
};
use astroport::common::{claim_ownership, drop_ownership_proposal, propose_new_owner};
use astroport::cosmwasm_ext::IntegerToDecimal;
use astroport::factory::PairType;
use astroport::pair::{
ConfigResponse, CumulativePricesResponse, FeeShareConfig, InstantiateMsg, StablePoolParams,
StablePoolUpdateParams, DEFAULT_SLIPPAGE, MAX_ALLOWED_SLIPPAGE, MAX_FEE_SHARE_BPS,
MIN_TRADE_SIZE,
};
use crate::migration::{migrate_config_from_v21, migrate_config_to_v210};
use astroport::observation::{query_observation, PrecommitObservation, OBSERVATIONS_SIZE};
use astroport::pair::{
Cw20HookMsg, ExecuteMsg, MigrateMsg, PoolResponse, QueryMsg, ReverseSimulationResponse,
SimulationResponse, StablePoolConfig,
};
use astroport::querier::{query_factory_config, query_fee_info, query_supply};
use astroport::token::InstantiateMsg as TokenInstantiateMsg;
use astroport::DecimalCheckedOps;
use astroport_circular_buffer::BufferManager;
use crate::error::ContractError;
use crate::math::{
calc_y, compute_d, AMP_PRECISION, MAX_AMP, MAX_AMP_CHANGE, MIN_AMP_CHANGING_TIME,
};
use crate::state::{
get_precision, store_precisions, Config, CONFIG, OBSERVATIONS, OWNERSHIP_PROPOSAL,
};
use crate::utils::{
accumulate_prices, accumulate_swap_sizes, adjust_precision, check_asset_infos, check_assets,
check_cw20_in_pool, compute_current_amp, compute_swap, determine_base_quote_amount,
get_share_in_assets, mint_liquidity_token_message, select_pools, SwapResult,
};
/// Contract name that is used for migration.
const CONTRACT_NAME: &str = "astroport-pair-stable";
/// Contract version that is used for migration.
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
/// A `reply` call code ID of sub-message.
const INSTANTIATE_TOKEN_REPLY_ID: u64 = 1;
/// Number of assets in the pool.
const N_COINS: usize = 2;
/// Creates a new contract with the specified parameters in [`InstantiateMsg`].
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
mut deps: DepsMut,
env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
check_asset_infos(deps.api, &msg.asset_infos)?;
if msg.asset_infos.len() != N_COINS {
return Err(ContractError::InvalidNumberOfAssets(N_COINS));
}
if msg.init_params.is_none() {
return Err(ContractError::InitParamsNotFound {});
}
let params: StablePoolParams = from_json(msg.init_params.unwrap())?;
if params.amp == 0 || params.amp > MAX_AMP {
return Err(ContractError::IncorrectAmp {});
}
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
let factory_addr = deps.api.addr_validate(&msg.factory_addr)?;
let greatest_precision = store_precisions(deps.branch(), &msg.asset_infos, &factory_addr)?;
// Initializing cumulative prices
let mut cumulative_prices = vec![];
for from_pool in &msg.asset_infos {
for to_pool in &msg.asset_infos {
if !from_pool.eq(to_pool) {
cumulative_prices.push((from_pool.clone(), to_pool.clone(), Uint128::zero()))
}
}
}
let config = Config {
owner: addr_opt_validate(deps.api, ¶ms.owner)?,
pair_info: PairInfo {
contract_addr: env.contract.address.clone(),
liquidity_token: Addr::unchecked(""),
asset_infos: msg.asset_infos.clone(),
pair_type: PairType::Stable {},
},
factory_addr,
block_time_last: 0,
init_amp: params.amp * AMP_PRECISION,
init_amp_time: env.block.time.seconds(),
next_amp: params.amp * AMP_PRECISION,
next_amp_time: env.block.time.seconds(),
greatest_precision,
cumulative_prices,
fee_share: None,
};
CONFIG.save(deps.storage, &config)?;
BufferManager::init(deps.storage, OBSERVATIONS, OBSERVATIONS_SIZE)?;
let token_name = format_lp_token_name(&msg.asset_infos, &deps.querier)?;
// Create LP token
let sub_msg = SubMsg::reply_on_success(
wasm_instantiate(
msg.token_code_id,
&TokenInstantiateMsg {
name: token_name,
symbol: "uLP".to_string(),
decimals: greatest_precision,
initial_balances: vec![],
mint: Some(MinterResponse {
minter: env.contract.address.to_string(),
cap: None,
}),
marketing: None,
},
vec![],
String::from("Astroport LP token"),
)?,
INSTANTIATE_TOKEN_REPLY_ID,
);
Ok(Response::new().add_submessage(sub_msg))
}
/// The entry point to the contract for processing replies from submessages.
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> Result<Response, ContractError> {
match msg {
Reply {
id: INSTANTIATE_TOKEN_REPLY_ID,
result:
SubMsgResult::Ok(SubMsgResponse {
data: Some(data), ..
}),
} => {
let mut config = CONFIG.load(deps.storage)?;
if config.pair_info.liquidity_token != Addr::unchecked("") {
return Err(ContractError::Unauthorized {});
}
let init_response = parse_instantiate_response_data(data.as_slice())
.map_err(|e| StdError::generic_err(format!("{e}")))?;
config.pair_info.liquidity_token =
deps.api.addr_validate(&init_response.contract_address)?;
CONFIG.save(deps.storage, &config)?;
Ok(Response::new()
.add_attribute("liquidity_token_addr", config.pair_info.liquidity_token))
}
_ => Err(ContractError::FailedToParseReply {}),
}
}
/// Exposes all the execute functions available in the contract.
///
/// ## Variants
/// * **ExecuteMsg::UpdateConfig { params: Binary }** Updates the contract configuration with the specified
/// input parameters.
///
/// * **ExecuteMsg::Receive(msg)** Receives a message of type [`Cw20ReceiveMsg`] and processes
/// it depending on the received template.
///
/// * **ExecuteMsg::ProvideLiquidity {
/// assets,
/// slippage_tolerance,
/// auto_stake,
/// receiver,
/// }** Provides liquidity in the pair using the specified input parameters.
///
/// * **ExecuteMsg::Swap {
/// offer_asset,
/// belief_price,
/// max_spread,
/// to,
/// }** Performs an swap using the specified parameters.
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::UpdateConfig { params } => update_config(deps, env, info, params),
ExecuteMsg::Receive(msg) => receive_cw20(deps, env, info, msg),
ExecuteMsg::ProvideLiquidity {
assets,
auto_stake,
receiver,
..
} => provide_liquidity(deps, env, info, assets, auto_stake, receiver),
ExecuteMsg::Swap {
offer_asset,
ask_asset_info,
belief_price,
max_spread,
to,
..
} => {
offer_asset.info.check(deps.api)?;
if !offer_asset.is_native_token() {
return Err(ContractError::Cw20DirectSwap {});
}
offer_asset.assert_sent_native_token_balance(&info)?;
let to_addr = addr_opt_validate(deps.api, &to)?;
swap(
deps,
env,
info.sender,
offer_asset,
ask_asset_info,
belief_price,
max_spread,
to_addr,
)
}
ExecuteMsg::ProposeNewOwner { owner, expires_in } => {
let cfg = CONFIG.load(deps.storage)?;
let factory_config = query_factory_config(&deps.querier, cfg.factory_addr.clone())?;
propose_new_owner(
deps,
info,
env,
owner,
expires_in,
cfg.owner.unwrap_or(factory_config.owner),
OWNERSHIP_PROPOSAL,
)
.map_err(|e| e.into())
}
ExecuteMsg::DropOwnershipProposal {} => {
let cfg = CONFIG.load(deps.storage)?;
let factory_config = query_factory_config(&deps.querier, cfg.factory_addr.clone())?;
drop_ownership_proposal(
deps,
info,
cfg.owner.unwrap_or(factory_config.owner),
OWNERSHIP_PROPOSAL,
)
.map_err(|e| e.into())
}
ExecuteMsg::ClaimOwnership {} => {
claim_ownership(deps, info, env, OWNERSHIP_PROPOSAL, |deps, new_owner| {
CONFIG.update::<_, StdError>(deps.storage, |mut config| {
config.owner = Some(new_owner);
Ok(config)
})?;
Ok(())
})
.map_err(|e| e.into())
}
}
}
/// Receives a message of type [`Cw20ReceiveMsg`] and processes it depending on the received template.
///
/// * **cw20_msg** is the CW20 receive message to process.
pub fn receive_cw20(
deps: DepsMut,
env: Env,
info: MessageInfo,
cw20_msg: Cw20ReceiveMsg,
) -> Result<Response, ContractError> {
match from_json(&cw20_msg.msg)? {
Cw20HookMsg::Swap {
ask_asset_info,
belief_price,
max_spread,
to,
} => {
let config = CONFIG.load(deps.storage)?;
// Only asset contract can execute this message
check_cw20_in_pool(&config, &info.sender)?;
let to_addr = addr_opt_validate(deps.api, &to)?;
swap(
deps,
env,
Addr::unchecked(cw20_msg.sender),
Asset {
info: AssetInfo::Token {
contract_addr: info.sender,
},
amount: cw20_msg.amount,
},
ask_asset_info,
belief_price,
max_spread,
to_addr,
)
}
Cw20HookMsg::WithdrawLiquidity { assets } => withdraw_liquidity(
deps,
env,
info,
Addr::unchecked(cw20_msg.sender),
cw20_msg.amount,
assets,
),
}
}
/// Provides liquidity with the specified input parameters.
///
/// * **assets** vector with assets available in the pool.
///
/// * **auto_stake** determines whether the resulting LP tokens are automatically staked in
/// the Generator contract to receive token incentives.
///
/// * **receiver** address that receives LP tokens. If this address isn't specified, the function will default to the caller.
///
/// NOTE - the address that wants to provide liquidity should approve the pair contract to pull its relevant tokens.
pub fn provide_liquidity(
deps: DepsMut,
env: Env,
info: MessageInfo,
assets: Vec<Asset>,
auto_stake: Option<bool>,
receiver: Option<String>,
) -> Result<Response, ContractError> {
check_assets(deps.api, &assets)?;
let auto_stake = auto_stake.unwrap_or(false);
let mut config = CONFIG.load(deps.storage)?;
info.funds
.assert_coins_properly_sent(&assets, &config.pair_info.asset_infos)?;
if assets.len() != config.pair_info.asset_infos.len() {
return Err(ContractError::InvalidNumberOfAssets(
config.pair_info.asset_infos.len(),
));
}
let pools: HashMap<_, _> = config
.pair_info
.query_pools(&deps.querier, &env.contract.address)?
.into_iter()
.map(|pool| (pool.info, pool.amount))
.collect();
let mut non_zero_flag = false;
let mut assets_collection = assets
.clone()
.into_iter()
.map(|asset| {
// Check that at least one asset is non-zero
if !asset.amount.is_zero() {
non_zero_flag = true;
}
// Get appropriate pool
let pool = pools
.get(&asset.info)
.copied()
.ok_or_else(|| ContractError::InvalidAsset(asset.info.to_string()))?;
Ok((asset, pool))
})
.collect::<Result<Vec<_>, ContractError>>()?;
// If some assets are omitted then add them explicitly with 0 deposit
pools.iter().for_each(|(pool_info, pool_amount)| {
if !assets.iter().any(|asset| asset.info.eq(pool_info)) {
assets_collection.push((
Asset {
amount: Uint128::zero(),
info: pool_info.clone(),
},
*pool_amount,
));
}
});
if !non_zero_flag {
return Err(ContractError::InvalidZeroAmount {});
}
let mut messages = vec![];
for (deposit, pool) in assets_collection.iter_mut() {
// We cannot put a zero amount into an empty pool.
if deposit.amount.is_zero() && pool.is_zero() {
return Err(ContractError::InvalidProvideLPsWithSingleToken {});
}
// Transfer only non-zero amount
if !deposit.amount.is_zero() {
// If the pool is a token contract, then we need to execute a TransferFrom msg to receive funds
if let AssetInfo::Token { contract_addr } = &deposit.info {
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: contract_addr.to_string(),
msg: to_json_binary(&Cw20ExecuteMsg::TransferFrom {
owner: info.sender.to_string(),
recipient: env.contract.address.to_string(),
amount: deposit.amount,
})?,
funds: vec![],
}))
} else {
// If the asset is a native token, the pool balance already increased
// To calculate the pool balance properly, we should subtract the user deposit from the recorded pool token amount
*pool = pool.checked_sub(deposit.amount)?;
}
}
}
let assets_collection = assets_collection
.iter()
.cloned()
.map(|(asset, pool)| {
let coin_precision = get_precision(deps.storage, &asset.info)?;
Ok((
asset.to_decimal_asset(coin_precision)?,
Decimal256::with_precision(pool, coin_precision)?,
))
})
.collect::<StdResult<Vec<(DecimalAsset, Decimal256)>>>()?;
let amp = compute_current_amp(&config, &env)?;
// Invariant (D) after deposit added
let new_balances = assets_collection
.iter()
.map(|(deposit, pool)| Ok(pool + deposit.amount))
.collect::<StdResult<Vec<_>>>()?;
let deposit_d = compute_d(amp, &new_balances)?;
let total_share = query_supply(&deps.querier, &config.pair_info.liquidity_token)?;
let share = if total_share.is_zero() {
let share = deposit_d
.to_uint128_with_precision(config.greatest_precision)?
.checked_sub(MINIMUM_LIQUIDITY_AMOUNT)
.map_err(|_| ContractError::MinimumLiquidityAmountError {})?;
// share cannot become zero after minimum liquidity subtraction
if share.is_zero() {
return Err(ContractError::MinimumLiquidityAmountError {});
}
messages.extend(mint_liquidity_token_message(
deps.querier,
&config,
&env.contract.address,
&env.contract.address,
MINIMUM_LIQUIDITY_AMOUNT,
false,
)?);
share
} else {
// Initial invariant (D)
let old_balances = assets_collection
.iter()
.map(|(_, pool)| *pool)
.collect_vec();
let init_d = compute_d(amp, &old_balances)?;
let share = Decimal256::with_precision(total_share, config.greatest_precision)?
.checked_multiply_ratio(deposit_d.saturating_sub(init_d), init_d)?
.to_uint128_with_precision(config.greatest_precision)?;
if share.is_zero() {
return Err(ContractError::LiquidityAmountTooSmall {});
}
share
};
// Mint LP token for the caller (or for the receiver if it was set)
let receiver = addr_opt_validate(deps.api, &receiver)?.unwrap_or_else(|| info.sender.clone());
messages.extend(mint_liquidity_token_message(
deps.querier,
&config,
&env.contract.address,
&receiver,
share,
auto_stake,
)?);
let pools = pools
.into_iter()
.map(|(info, amount)| {
let precision = get_precision(deps.storage, &info)?;
Ok(DecimalAsset {
info,
amount: Decimal256::with_precision(amount, precision)?,
})
})
.collect::<StdResult<Vec<_>>>()?;
if accumulate_prices(deps.storage, &env, &mut config, &pools)? {
CONFIG.save(deps.storage, &config)?;
}
Ok(Response::new().add_messages(messages).add_attributes(vec![
attr("action", "provide_liquidity"),
attr("sender", info.sender),
attr("receiver", receiver),
attr("assets", assets.iter().join(", ")),
attr("share", share),
]))
}
/// Withdraw liquidity from the pool.
/// * **sender** is the address that will receive assets back from the pair contract.
///
/// * **amount** is the amount of LP tokens to burn.
pub fn withdraw_liquidity(
deps: DepsMut,
env: Env,
info: MessageInfo,
sender: Addr,
amount: Uint128,
assets: Vec<Asset>,
) -> Result<Response, ContractError> {
let mut config = CONFIG.load(deps.storage)?;
if info.sender != config.pair_info.liquidity_token {
return Err(ContractError::Unauthorized {});
}
let (pools, total_share) = pool_info(deps.querier, &config)?;
let refund_assets = if assets.is_empty() {
// Usual withdraw (balanced)
get_share_in_assets(&pools, amount, total_share)
} else {
return Err(StdError::generic_err("Imbalanced withdraw is currently disabled").into());
};
let mut messages = refund_assets
.clone()
.into_iter()
.map(|asset| asset.into_msg(&sender))
.collect::<StdResult<Vec<_>>>()?;
messages.push(
wasm_execute(
&config.pair_info.liquidity_token,
&Cw20ExecuteMsg::Burn { amount },
vec![],
)?
.into(),
);
let pools = pools
.iter()
.map(|pool| {
let precision = get_precision(deps.storage, &pool.info)?;
pool.to_decimal_asset(precision)
})
.collect::<StdResult<Vec<DecimalAsset>>>()?;
if accumulate_prices(deps.storage, &env, &mut config, &pools)? {
CONFIG.save(deps.storage, &config)?;
}
Ok(Response::new().add_messages(messages).add_attributes(vec![
attr("action", "withdraw_liquidity"),
attr("sender", sender),
attr("withdrawn_share", amount),
attr("refund_assets", refund_assets.iter().join(", ")),
]))
}
/// Performs an swap operation with the specified parameters.
///
/// * **sender** is the sender of the swap operation.
///
/// * **offer_asset** proposed asset for swapping.
///
/// * **belief_price** is used to calculate the maximum swap spread.
///
/// * **max_spread** sets the maximum spread of the swap operation.
///
/// * **to** sets the recipient of the swap operation.
///
/// NOTE - the address that wants to swap should approve the pair contract to pull the offer token.
#[allow(clippy::too_many_arguments)]
pub fn swap(
deps: DepsMut,
env: Env,
sender: Addr,
offer_asset: Asset,
ask_asset_info: Option<AssetInfo>,
belief_price: Option<Decimal>,
max_spread: Option<Decimal>,
to: Option<Addr>,
) -> Result<Response, ContractError> {
let mut config = CONFIG.load(deps.storage)?;
// If the asset balance already increased
// We should subtract the user deposit from the pool offer asset amount
let pools = config
.pair_info
.query_pools(&deps.querier, &env.contract.address)?
.into_iter()
.map(|mut pool| {
if pool.info.equal(&offer_asset.info) {
pool.amount = pool.amount.checked_sub(offer_asset.amount)?;
}
let token_precision = get_precision(deps.storage, &pool.info)?;
Ok(DecimalAsset {
info: pool.info,
amount: Decimal256::with_precision(pool.amount, token_precision)?,
})
})
.collect::<StdResult<Vec<_>>>()?;
let (offer_pool, ask_pool) =
select_pools(Some(&offer_asset.info), ask_asset_info.as_ref(), &pools)?;
let offer_precision = get_precision(deps.storage, &offer_pool.info)?;
// Check if the liquidity is non-zero
check_swap_parameters(
pools
.iter()
.map(|pool| {
pool.amount
.to_uint128_with_precision(get_precision(deps.storage, &pool.info)?)
})
.collect::<StdResult<Vec<Uint128>>>()?,
offer_asset.amount,
)?;
let offer_asset_dec = offer_asset.to_decimal_asset(offer_precision)?;
let SwapResult {
return_amount,
spread_amount,
} = compute_swap(
deps.storage,
&env,
&config,
&offer_asset_dec,
&offer_pool,
&ask_pool,
&pools,
)?;
// Get fee info from the factory
let fee_info = query_fee_info(
&deps.querier,
&config.factory_addr,
config.pair_info.pair_type.clone(),
)?;
let commission_amount = fee_info.total_fee_rate.checked_mul_uint128(return_amount)?;
let return_amount = return_amount.saturating_sub(commission_amount);
// Check the max spread limit (if it was specified)
assert_max_spread(
belief_price,
max_spread,
offer_asset.amount,
return_amount + commission_amount,
spread_amount,
)?;
let receiver = to.unwrap_or_else(|| sender.clone());
let return_asset = Asset {
info: ask_pool.info.clone(),
amount: return_amount,
};
let mut messages = vec![];
if !return_amount.is_zero() {
messages.push(return_asset.into_msg(receiver.clone())?)
}
// If this pool is configured to share fees, calculate the amount to send
// to the receiver and add the transfer message
// The calculation works as follows: We take the share percentage first,
// and the remainder is then split between LPs and maker
let mut fees_commission_amount = commission_amount;
let mut fee_share_amount = Uint128::zero();
if let Some(ref fee_share) = config.fee_share {
// Calculate the fee share amount from the full commission amount
let share_fee_rate = Decimal::from_ratio(fee_share.bps, 10000u16);
fee_share_amount = fees_commission_amount * share_fee_rate;
if !fee_share_amount.is_zero() {
// Subtract the fee share amount from the commission
fees_commission_amount = fees_commission_amount.saturating_sub(fee_share_amount);
// Build send message for the shared amount
let fee_share_msg = Asset {
info: ask_pool.info.clone(),
amount: fee_share_amount,
}
.into_msg(&fee_share.recipient)?;
messages.push(fee_share_msg);
}
}
// Compute the Maker fee
let mut maker_fee_amount = Uint128::zero();
if let Some(fee_address) = fee_info.fee_address {
if let Some(f) = calculate_maker_fee(
&ask_pool.info,
fees_commission_amount,
fee_info.maker_fee_rate,
) {
maker_fee_amount = f.amount;
messages.push(f.into_msg(fee_address)?);
}
}
if accumulate_prices(deps.storage, &env, &mut config, &pools)? {
CONFIG.save(deps.storage, &config)?;
}
// Store observation from precommit data
accumulate_swap_sizes(deps.storage, &env)?;
// Store time series data in precommit observation.
// Skipping small unsafe values which can seriously mess oracle price due to rounding errors.
// This data will be reflected in observations on the next action.
let ask_precision = get_precision(deps.storage, &ask_pool.info)?;
if offer_asset_dec.amount >= MIN_TRADE_SIZE
&& return_amount.to_decimal256(ask_precision)? >= MIN_TRADE_SIZE
{
// Store time series data
let (base_amount, quote_amount) =
determine_base_quote_amount(&pools, &offer_asset, return_amount)?;
PrecommitObservation::save(deps.storage, &env, base_amount, quote_amount)?;
}
Ok(Response::new()
.add_messages(
// 1. send collateral tokens from the contract to a user
// 2. send inactive commission fees to the Maker contract
messages,
)
.add_attributes(vec![
attr("action", "swap"),
attr("sender", sender),
attr("receiver", receiver),
attr("offer_asset", offer_asset.info.to_string()),
attr("ask_asset", ask_pool.info.to_string()),
attr("offer_amount", offer_asset.amount),
attr("return_amount", return_amount),
attr("spread_amount", spread_amount),
attr("commission_amount", commission_amount),
attr("maker_fee_amount", maker_fee_amount),
attr("fee_share_amount", fee_share_amount),
]))
}
/// Calculates the amount of fees the Maker contract gets according to specified pair parameters.
/// Returns a [`None`] if the Maker fee is zero, otherwise returns a [`Asset`] struct with the specified attributes.
///
/// * **pool_info** contains information about the pool asset for which the commission will be calculated.
///
/// * **commission_amount** is the total amount of fees charged for a swap.
///
/// * **maker_commission_rate** is the percentage of fees that go to the Maker contract.
pub fn calculate_maker_fee(
pool_info: &AssetInfo,
commission_amount: Uint128,
maker_commission_rate: Decimal,
) -> Option<Asset> {
let maker_fee: Uint128 = commission_amount * maker_commission_rate;
if maker_fee.is_zero() {
return None;
}
Some(Asset {
info: pool_info.clone(),
amount: maker_fee,
})
}
/// Exposes all the queries available in the contract.
/// ## Queries
/// * **QueryMsg::Pair {}** Returns information about the pair in an object of type [`PairInfo`].
///
/// * **QueryMsg::Pool {}** Returns information about the amount of assets in the pair contract as
/// well as the amount of LP tokens issued using an object of type [`PoolResponse`].
///
/// * **QueryMsg::Share { amount }** Returns the amount of assets that could be withdrawn from the pool
/// using a specific amount of LP tokens. The result is returned in a vector that contains objects of type [`Asset`].
///
/// * **QueryMsg::Simulation { offer_asset }** Returns the result of a swap simulation using a [`SimulationResponse`] object.
///
/// * **QueryMsg::ReverseSimulation { ask_asset }** Returns the result of a reverse swap simulation using
/// a [`ReverseSimulationResponse`] object.
///
/// * **QueryMsg::CumulativePrices {}** Returns information about cumulative prices for the assets in the
/// pool using a [`CumulativePricesResponse`] object.
///
/// * **QueryMsg::Config {}** Returns the configuration for the pair contract using a [`ConfigResponse`] object.
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::Pair {} => to_json_binary(&CONFIG.load(deps.storage)?.pair_info),
QueryMsg::Pool {} => to_json_binary(&query_pool(deps)?),
QueryMsg::Share { amount } => to_json_binary(&query_share(deps, amount)?),
QueryMsg::Simulation {
offer_asset,
ask_asset_info,
} => to_json_binary(&query_simulation(deps, env, offer_asset, ask_asset_info)?),
QueryMsg::ReverseSimulation {
offer_asset_info,
ask_asset,
} => to_json_binary(&query_reverse_simulation(
deps,
env,
ask_asset,
offer_asset_info,
)?),
QueryMsg::CumulativePrices {} => to_json_binary(&query_cumulative_prices(deps, env)?),
QueryMsg::Observe { seconds_ago } => {
to_json_binary(&query_observation(deps, env, OBSERVATIONS, seconds_ago)?)
}
QueryMsg::Config {} => to_json_binary(&query_config(deps, env)?),
QueryMsg::QueryComputeD {} => to_json_binary(&query_compute_d(deps, env)?),
_ => Err(StdError::generic_err("Query is not supported")),
}
}
/// Returns the amounts of assets in the pair contract as well as the amount of LP
/// tokens currently minted in an object of type [`PoolResponse`].
pub fn query_pool(deps: Deps) -> StdResult<PoolResponse> {
let config = CONFIG.load(deps.storage)?;
let (assets, total_share) = pool_info(deps.querier, &config)?;
let resp = PoolResponse {
assets,
total_share,
};
Ok(resp)
}
/// Returns the amount of assets that could be withdrawn from the pool using a specific amount of LP tokens.
/// The result is returned in a vector that contains objects of type [`Asset`].
///
/// * **amount** is the amount of LP tokens for which we calculate associated amounts of assets.
pub fn query_share(deps: Deps, amount: Uint128) -> StdResult<Vec<Asset>> {
let config = CONFIG.load(deps.storage)?;
let (pools, total_share) = pool_info(deps.querier, &config)?;
let refund_assets = get_share_in_assets(&pools, amount, total_share);
Ok(refund_assets)
}
/// Returns information about a swap simulation in a [`SimulationResponse`] object.
///
/// * **offer_asset** is the asset to swap as well as an amount of the said asset.
pub fn query_simulation(
deps: Deps,
env: Env,
offer_asset: Asset,
ask_asset_info: Option<AssetInfo>,
) -> StdResult<SimulationResponse> {
let config = CONFIG.load(deps.storage)?;
let pools = config.pair_info.query_pools_decimal(
&deps.querier,
&config.pair_info.contract_addr,
&config.factory_addr,
)?;
let (offer_pool, ask_pool) =
select_pools(Some(&offer_asset.info), ask_asset_info.as_ref(), &pools)
.map_err(|err| StdError::generic_err(format!("{err}")))?;
let offer_precision = get_precision(deps.storage, &offer_pool.info)?;
if check_swap_parameters(
pools
.iter()
.map(|pool| {
pool.amount
.to_uint128_with_precision(get_precision(deps.storage, &pool.info)?)
})
.collect::<StdResult<Vec<Uint128>>>()?,
offer_asset.amount,
)
.is_err()
{
return Ok(SimulationResponse {
return_amount: Uint128::zero(),
spread_amount: Uint128::zero(),
commission_amount: Uint128::zero(),
});
}
let SwapResult {
return_amount,
spread_amount,
} = compute_swap(
deps.storage,
&env,
&config,
&offer_asset.to_decimal_asset(offer_precision)?,
&offer_pool,
&ask_pool,
&pools,
)
.map_err(|err| StdError::generic_err(format!("{err}")))?;
// Get fee info from factory
let fee_info = query_fee_info(
&deps.querier,
&config.factory_addr,
config.pair_info.pair_type.clone(),
)?;
let commission_amount = fee_info.total_fee_rate.checked_mul_uint128(return_amount)?;
let return_amount = return_amount.saturating_sub(commission_amount);
Ok(SimulationResponse {
return_amount,
spread_amount,
commission_amount,
})
}
/// Returns information about a reverse swap simulation in a [`ReverseSimulationResponse`] object.
///
/// * **ask_asset** is the asset to swap to as well as the desired amount of ask
/// assets to receive from the swap.
///
/// * **offer_asset_info** is optional field which specifies the asset to swap from.
/// May be omitted only in case the pool length is 2.
pub fn query_reverse_simulation(
deps: Deps,
env: Env,
ask_asset: Asset,
offer_asset_info: Option<AssetInfo>,
) -> StdResult<ReverseSimulationResponse> {
let config = CONFIG.load(deps.storage)?;
let pools = config.pair_info.query_pools_decimal(
&deps.querier,
&config.pair_info.contract_addr,
&config.factory_addr,
)?;
let (offer_pool, ask_pool) =
select_pools(offer_asset_info.as_ref(), Some(&ask_asset.info), &pools)
.map_err(|err| StdError::generic_err(format!("{err}")))?;
let offer_precision = get_precision(deps.storage, &offer_pool.info)?;
let ask_precision = get_precision(deps.storage, &ask_asset.info)?;
// Check the swap parameters are valid
if check_swap_parameters(
pools
.iter()
.map(|pool| {
pool.amount
.to_uint128_with_precision(get_precision(deps.storage, &pool.info)?)
})
.collect::<StdResult<Vec<Uint128>>>()?,
ask_asset.amount,
)
.is_err()
{
return Ok(ReverseSimulationResponse {
offer_amount: Uint128::zero(),
spread_amount: Uint128::zero(),
commission_amount: Uint128::zero(),
});
}
// Get fee info from the factory
let fee_info = query_fee_info(
&deps.querier,