-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathcontract.rs
More file actions
614 lines (541 loc) · 21.4 KB
/
Copy pathcontract.rs
File metadata and controls
614 lines (541 loc) · 21.4 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
use std::collections::HashSet;
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
attr, ensure, to_json_binary, Binary, CosmosMsg, Deps, DepsMut, Empty, Env, MessageInfo, Order,
Reply, ReplyOn, Response, StdError, StdResult, SubMsg, SubMsgResponse, SubMsgResult, WasmMsg,
};
use cw2::{get_contract_version, set_contract_version};
use cw_utils::parse_instantiate_response_data;
use itertools::Itertools;
use astroport::asset::{addr_opt_validate, AssetInfo, PairInfo};
use astroport::common::{claim_ownership, drop_ownership_proposal, propose_new_owner};
use astroport::factory::{
Config, ConfigResponse, ExecuteMsg, FeeInfoResponse, InstantiateMsg, PairConfig, PairType,
PairsResponse, QueryMsg, TrackerConfig,
};
use astroport::incentives::ExecuteMsg::DeactivatePool;
use astroport::pair::InstantiateMsg as PairInstantiateMsg;
use crate::error::ContractError;
use crate::migration::migrate_pair_configs;
use crate::querier::query_pair_info;
use crate::state::{
check_asset_infos, pair_key, read_pairs, TmpPairInfo, CONFIG, OWNERSHIP_PROPOSAL, PAIRS,
PAIR_CONFIGS, TMP_PAIR_INFO, TRACKER_CONFIG,
};
/// Contract name that is used for migration.
const CONTRACT_NAME: &str = "astroport-factory";
/// Contract version that is used for migration.
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
/// A `reply` call code ID used in a sub-message.
const INSTANTIATE_PAIR_REPLY_ID: u64 = 1;
/// Creates a new contract with the specified parameters packed in the `msg` variable.
///
/// * **msg** is message which contains the parameters used for creating the contract.
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
let mut config = Config {
owner: deps.api.addr_validate(&msg.owner)?,
token_code_id: msg.token_code_id,
fee_address: None,
generator_address: None,
whitelist_code_id: msg.whitelist_code_id,
coin_registry_address: deps.api.addr_validate(&msg.coin_registry_address)?,
};
config.generator_address = addr_opt_validate(deps.api, &msg.generator_address)?;
config.fee_address = addr_opt_validate(deps.api, &msg.fee_address)?;
let config_set: HashSet<String> = msg
.pair_configs
.iter()
.map(|pc| pc.pair_type.to_string())
.collect();
if config_set.len() != msg.pair_configs.len() {
return Err(ContractError::PairConfigDuplicate {});
}
for pc in msg.pair_configs.iter() {
// Validate total and maker fee bps
if !pc.valid_fee_bps() {
return Err(ContractError::PairConfigInvalidFeeBps {});
}
PAIR_CONFIGS.save(deps.storage, pc.pair_type.to_string(), pc)?;
}
CONFIG.save(deps.storage, &config)?;
if let Some(tracker_config) = msg.tracker_config {
TRACKER_CONFIG.save(
deps.storage,
&TrackerConfig {
code_id: tracker_config.code_id,
token_factory_addr: deps
.api
.addr_validate(&tracker_config.token_factory_addr)?
.to_string(),
},
)?;
}
Ok(Response::new())
}
/// Data structure used to update general contract parameters.
pub struct UpdateConfig {
/// This is the CW20 token contract code identifier
token_code_id: Option<u64>,
/// Contract address to send governance fees to (the Maker)
fee_address: Option<String>,
/// Generator contract address
generator_address: Option<String>,
/// CW1 whitelist contract code id used to store 3rd party staking rewards
whitelist_code_id: Option<u64>,
coin_registry_address: Option<String>,
}
/// Exposes all the execute functions available in the contract.
/// * **msg** is an object of type [`ExecuteMsg`].
///
/// ## Variants
/// * **ExecuteMsg::UpdateConfig {
/// token_code_id,
/// fee_address,
/// generator_address,
/// }** Updates general contract parameters.
///
/// * **ExecuteMsg::UpdatePairConfig { config }** Updates a pair type
/// * configuration or creates a new pair type if a [`Custom`] name is used (which hasn't been used before).
///
/// * **ExecuteMsg::CreatePair {
/// pair_type,
/// asset_infos,
/// init_params,
/// }** Creates a new pair with the specified input parameters.
///
/// * **ExecuteMsg::Deregister { asset_infos }** Removes an existing pair from the factory.
/// * The asset information is for the assets that are traded in the pair.
///
/// * **ExecuteMsg::ProposeNewOwner { owner, expires_in }** Creates a request to change contract ownership.
///
/// * **ExecuteMsg::DropOwnershipProposal {}** Removes a request to change contract ownership.
///
/// * **ExecuteMsg::ClaimOwnership {}** Claims contract ownership.
#[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 {
token_code_id,
fee_address,
generator_address,
whitelist_code_id,
coin_registry_address,
} => execute_update_config(
deps,
info,
UpdateConfig {
token_code_id,
fee_address,
generator_address,
whitelist_code_id,
coin_registry_address,
},
),
ExecuteMsg::UpdatePairConfig { config } => execute_update_pair_config(deps, info, config),
ExecuteMsg::CreatePair {
pair_type,
asset_infos,
init_params,
} => execute_create_pair(deps, info, env, pair_type, asset_infos, init_params),
ExecuteMsg::Deregister { asset_infos } => deregister(deps, info, asset_infos),
ExecuteMsg::ProposeNewOwner { owner, expires_in } => {
let config = CONFIG.load(deps.storage)?;
propose_new_owner(
deps,
info,
env,
owner,
expires_in,
config.owner,
OWNERSHIP_PROPOSAL,
)
.map_err(Into::into)
}
ExecuteMsg::DropOwnershipProposal {} => {
let config = CONFIG.load(deps.storage)?;
drop_ownership_proposal(deps, info, config.owner, OWNERSHIP_PROPOSAL)
.map_err(Into::into)
}
ExecuteMsg::ClaimOwnership {} => {
claim_ownership(deps, info, env, OWNERSHIP_PROPOSAL, |deps, new_owner| {
CONFIG
.update::<_, StdError>(deps.storage, |mut v| {
v.owner = new_owner;
Ok(v)
})
.map(|_| ())
})
.map_err(Into::into)
}
ExecuteMsg::UpdateTrackerConfig {
tracker_code_id,
token_factory_addr,
} => update_tracker_config(deps, info, tracker_code_id, token_factory_addr),
}
}
/// Updates general contract settings.
///
/// * **param** is an object of type [`UpdateConfig`] that contains the parameters to update.
///
/// ## Executor
/// Only the owner can execute this.
pub fn execute_update_config(
deps: DepsMut,
info: MessageInfo,
param: UpdateConfig,
) -> Result<Response, ContractError> {
let mut config = CONFIG.load(deps.storage)?;
// Permission check
if info.sender != config.owner {
return Err(ContractError::Unauthorized {});
}
if let Some(fee_address) = param.fee_address {
// Validate address format
config.fee_address = Some(deps.api.addr_validate(&fee_address)?);
}
if let Some(generator_address) = param.generator_address {
// Validate the address format
config.generator_address = Some(deps.api.addr_validate(&generator_address)?);
}
if let Some(token_code_id) = param.token_code_id {
config.token_code_id = token_code_id;
}
if let Some(code_id) = param.whitelist_code_id {
config.whitelist_code_id = code_id;
}
if let Some(coin_registry_address) = param.coin_registry_address {
config.coin_registry_address = deps.api.addr_validate(&coin_registry_address)?;
}
CONFIG.save(deps.storage, &config)?;
Ok(Response::new().add_attribute("action", "update_config"))
}
/// Updates a pair type's configuration.
///
/// * **pair_config** is an object of type [`PairConfig`] that contains the pair type information to update.
///
/// ## Executor
/// Only the owner can execute this.
pub fn execute_update_pair_config(
deps: DepsMut,
info: MessageInfo,
pair_config: PairConfig,
) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
// Permission check
if info.sender != config.owner {
return Err(ContractError::Unauthorized {});
}
// Validate total and maker fee bps
if !pair_config.valid_fee_bps() {
return Err(ContractError::PairConfigInvalidFeeBps {});
}
// Check if whitelist is valid
if let Some(whitelist) = &pair_config.whitelist {
let unique_whitelist: HashSet<String> = whitelist.iter().cloned().collect();
if unique_whitelist.len() != whitelist.len() {
return Err(ContractError::PairConfigDuplicateWhitelist {});
}
// Validate addresses in whitelist
for addr in unique_whitelist.iter() {
deps.api
.addr_validate(addr)
.map_err(|_| ContractError::PairConfigInvalidWhitelistAddress {})?;
}
}
PAIR_CONFIGS.save(
deps.storage,
pair_config.pair_type.to_string(),
&pair_config,
)?;
Ok(Response::new().add_attribute("action", "update_pair_config"))
}
/// Creates a new pair of `pair_type` with the assets specified in `asset_infos`.
///
/// * **pair_type** is the pair type of the newly created pair.
///
/// * **asset_infos** is a vector with assets for which we create a pair.
///
/// * **init_params** These are packed params used for custom pair types that need extra data to be instantiated.
pub fn execute_create_pair(
deps: DepsMut,
info: MessageInfo,
env: Env,
pair_type: PairType,
asset_infos: Vec<AssetInfo>,
init_params: Option<Binary>,
) -> Result<Response, ContractError> {
check_asset_infos(deps.api, &asset_infos)?;
let config = CONFIG.load(deps.storage)?;
if PAIRS.has(deps.storage, &pair_key(&asset_infos)) {
return Err(ContractError::PairWasCreated {});
}
// Get pair type from config
let pair_config = PAIR_CONFIGS
.load(deps.storage, pair_type.to_string())
.map_err(|_| ContractError::PairConfigNotFound {})?;
if pair_config.permissioned
&& info.sender != config.owner
&& !is_whitelisted(&pair_config, &info.sender.to_string())
{
return Err(ContractError::Unauthorized {});
}
// Check if pair config is disabled
if pair_config.is_disabled {
return Err(ContractError::PairConfigDisabled {});
}
let pair_key = pair_key(&asset_infos);
TMP_PAIR_INFO.save(deps.storage, &TmpPairInfo { pair_key })?;
let sub_msg: Vec<SubMsg> = vec![SubMsg {
id: INSTANTIATE_PAIR_REPLY_ID,
msg: WasmMsg::Instantiate {
admin: Some(config.owner.to_string()),
code_id: pair_config.code_id,
msg: to_json_binary(&PairInstantiateMsg {
pair_type,
asset_infos: asset_infos.clone(),
token_code_id: config.token_code_id,
factory_addr: env.contract.address.to_string(),
init_params,
})?,
// Pass executor funds to pair contract to pay for LP token creation
funds: info.funds,
label: "Astroport pair".to_string(),
}
.into(),
gas_limit: None,
reply_on: ReplyOn::Success,
}];
Ok(Response::new()
.add_submessages(sub_msg)
.add_attributes(vec![
attr("action", "create_pair"),
attr("pair", asset_infos.iter().join("-")),
]))
}
fn is_whitelisted(pair_config: &PairConfig, sender: &String) -> bool {
if let Some(whitelist) = &pair_config.whitelist {
whitelist.contains(sender)
} else {
false
}
}
/// 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_PAIR_REPLY_ID,
result:
SubMsgResult::Ok(SubMsgResponse {
data: Some(data), ..
}),
} => {
let tmp = TMP_PAIR_INFO.load(deps.storage)?;
if PAIRS.has(deps.storage, &tmp.pair_key) {
return Err(ContractError::PairWasRegistered {});
}
let init_response = parse_instantiate_response_data(data.as_slice())
.map_err(|e| StdError::generic_err(format!("{e}")))?;
let pair_contract = deps.api.addr_validate(&init_response.contract_address)?;
PAIRS.save(deps.storage, &tmp.pair_key, &pair_contract)?;
Ok(Response::new().add_attributes(vec![
attr("action", "register"),
attr("pair_contract_addr", pair_contract),
]))
}
_ => Err(ContractError::FailedToParseReply {}),
}
}
/// Removes an existing pair from the factory.
///
/// * **asset_infos** is a vector with assets for which we deregister the pair.
///
/// ## Executor
/// Only the owner can execute this.
pub fn deregister(
deps: DepsMut,
info: MessageInfo,
asset_infos: Vec<AssetInfo>,
) -> Result<Response, ContractError> {
check_asset_infos(deps.api, &asset_infos)?;
let config = CONFIG.load(deps.storage)?;
if info.sender != config.owner {
return Err(ContractError::Unauthorized {});
}
let pair_addr = PAIRS.load(deps.storage, &pair_key(&asset_infos))?;
PAIRS.remove(deps.storage, &pair_key(&asset_infos));
let mut messages: Vec<CosmosMsg> = vec![];
if let Some(generator) = config.generator_address {
let pair_info = query_pair_info(&deps.querier, &pair_addr)?;
// sets the allocation point to zero for the lp_token
messages.push(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: generator.to_string(),
msg: to_json_binary(&DeactivatePool {
lp_token: pair_info.liquidity_token.to_string(),
})?,
funds: vec![],
}));
}
Ok(Response::new().add_messages(messages).add_attributes(vec![
attr("action", "deregister"),
attr("pair_contract_addr", pair_addr),
]))
}
pub fn update_tracker_config(
deps: DepsMut,
info: MessageInfo,
tracker_code_id: u64,
token_factory_addr: Option<String>,
) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
ensure!(info.sender == config.owner, ContractError::Unauthorized {});
if let Some(mut tracker_config) = TRACKER_CONFIG.may_load(deps.storage)? {
tracker_config.code_id = tracker_code_id;
TRACKER_CONFIG.save(deps.storage, &tracker_config)?;
} else {
let tokenfactory_tracker =
token_factory_addr.ok_or(StdError::generic_err("token_factory_addr is required"))?;
TRACKER_CONFIG.save(
deps.storage,
&TrackerConfig {
code_id: tracker_code_id,
token_factory_addr: tokenfactory_tracker,
},
)?;
}
Ok(Response::new()
.add_attribute("action", "update_tracker_config")
.add_attribute("code_id", tracker_code_id.to_string()))
}
/// Exposes all the queries available in the contract.
///
/// ## Queries
/// * **QueryMsg::Config {}** Returns general contract parameters using a custom [`ConfigResponse`] structure.
///
/// * **QueryMsg::Pair { asset_infos }** Returns a [`PairInfo`] object with information about a specific Astroport pair.
///
/// * **QueryMsg::Pairs { start_after, limit }** Returns an array that contains items of type [`PairInfo`].
/// This returns information about multiple Astroport pairs
///
/// * **QueryMsg::FeeInfo { pair_type }** Returns the fee structure (total and maker fees) for a specific pair type.
///
/// * **QueryMsg::BlacklistedPairTypes {}** Returns a vector that contains blacklisted pair types (pair types that cannot get ASTRO emissions).
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::Config {} => to_json_binary(&query_config(deps)?),
QueryMsg::Pair { asset_infos } => to_json_binary(&query_pair(deps, asset_infos)?),
QueryMsg::Pairs { start_after, limit } => {
to_json_binary(&query_pairs(deps, start_after, limit)?)
}
QueryMsg::FeeInfo { pair_type } => to_json_binary(&query_fee_info(deps, pair_type)?),
QueryMsg::BlacklistedPairTypes {} => to_json_binary(&query_blacklisted_pair_types(deps)?),
QueryMsg::TrackerConfig {} => to_json_binary(&query_tracker_config(deps)?),
}
}
/// Returns a vector that contains blacklisted pair types
pub fn query_blacklisted_pair_types(deps: Deps) -> StdResult<Vec<PairType>> {
PAIR_CONFIGS
.range(deps.storage, None, None, Order::Ascending)
.filter_map(|result| match result {
Ok(v) => {
if v.1.is_disabled || v.1.is_generator_disabled {
Some(Ok(v.1.pair_type))
} else {
None
}
}
Err(e) => Some(Err(e)),
})
.collect()
}
/// Returns general contract parameters using a custom [`ConfigResponse`] structure.
pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> {
let config = CONFIG.load(deps.storage)?;
let resp = ConfigResponse {
owner: config.owner,
token_code_id: config.token_code_id,
pair_configs: PAIR_CONFIGS
.range(deps.storage, None, None, Order::Ascending)
.map(|item| Ok(item?.1))
.collect::<StdResult<Vec<_>>>()?,
fee_address: config.fee_address,
generator_address: config.generator_address,
whitelist_code_id: config.whitelist_code_id,
coin_registry_address: config.coin_registry_address,
};
Ok(resp)
}
/// Returns a pair's data using the assets in `asset_infos` as input (those being the assets that are traded in the pair).
/// * **asset_infos** is a vector with assets traded in the pair.
pub fn query_pair(deps: Deps, asset_infos: Vec<AssetInfo>) -> StdResult<PairInfo> {
let pair_addr = PAIRS.load(deps.storage, &pair_key(&asset_infos))?;
query_pair_info(&deps.querier, pair_addr)
}
/// Returns a vector with pair data that contains items of type [`PairInfo`]. Querying starts at `start_after` and returns `limit` pairs.
/// * **start_after** is a field which accepts a vector with items of type [`AssetInfo`].
/// This is the pair from which we start a query.
///
/// * **limit** sets the number of pairs to be retrieved.
pub fn query_pairs(
deps: Deps,
start_after: Option<Vec<AssetInfo>>,
limit: Option<u32>,
) -> StdResult<PairsResponse> {
let pairs = read_pairs(deps, start_after, limit)?
.iter()
.map(|pair_addr| query_pair_info(&deps.querier, pair_addr))
.collect::<StdResult<Vec<_>>>()?;
Ok(PairsResponse { pairs })
}
/// Returns the fee setup for a specific pair type using a [`FeeInfoResponse`] struct.
/// * **pair_type** is a struct that represents the fee information (total and maker fees) for a specific pair type.
pub fn query_fee_info(deps: Deps, pair_type: PairType) -> StdResult<FeeInfoResponse> {
let config = CONFIG.load(deps.storage)?;
let pair_config = PAIR_CONFIGS.load(deps.storage, pair_type.to_string())?;
Ok(FeeInfoResponse {
fee_address: config.fee_address,
total_fee_bps: pair_config.total_fee_bps,
maker_fee_bps: pair_config.maker_fee_bps,
})
}
pub fn query_tracker_config(deps: Deps) -> StdResult<TrackerConfig> {
let tracker_config = TRACKER_CONFIG.load(deps.storage).map_err(|_| {
StdError::generic_err("Tracker config is not set in the factory. It can't be provided")
})?;
Ok(TrackerConfig {
code_id: tracker_config.code_id,
token_factory_addr: tracker_config.token_factory_addr,
})
}
/// Manages the contract migration.
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(deps: DepsMut, _env: Env, _msg: Empty) -> Result<Response, ContractError> {
let contract_version = get_contract_version(deps.storage)?;
match contract_version.contract.as_ref() {
"astroport-factory" => match contract_version.version.as_ref() {
"1.8.0" | "1.8.1" | "1.9.0" => migrate_pair_configs(deps.storage)?,
_ => return Err(ContractError::MigrationError {}),
},
_ => return Err(ContractError::MigrationError {}),
}
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
Ok(Response::new()
.add_attribute("previous_contract_name", &contract_version.contract)
.add_attribute("previous_contract_version", &contract_version.version)
.add_attribute("new_contract_name", CONTRACT_NAME)
.add_attribute("new_contract_version", CONTRACT_VERSION))
}