Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cargo clippy, DO NOT MERGE #16

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 49 additions & 49 deletions treasury/src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ impl Contract {
/// ```
pub fn is_allowed_action(&self, action: &ActionType) -> bool {
self.approved_action_types
.contains(&self.get_action_label(&action))
.contains(&self.get_action_label(action))
}

/// Accept a list of actions, parse for when and how they should get stored
Expand All @@ -214,7 +214,7 @@ impl Contract {
match action.get_time_type() {
ActionTime::Timeout => {
assert!(action.timeout.is_some());
let timeout = action.timeout.unwrap_or(U128::from(0));
let timeout = action.timeout.unwrap_or_else(|| U128::from(0));
assert_ne!(timeout.0, 0);
log!(
"block {:?}, tssss: {:?}, ts: {:?}",
Expand All @@ -228,7 +228,7 @@ impl Contract {
let mut ts_actions = self
.timeout_actions
.get(&timeout.0)
.unwrap_or(VecDeque::new());
.unwrap_or_else(VecDeque::new);

// place with priority, then write to storage
if action.priority > 0 {
Expand Down Expand Up @@ -270,20 +270,20 @@ impl Contract {
/// ```bash
/// near view treasury.testnet has_timeout_actions
/// ```
pub fn has_timeout_actions(&self) -> (bool, Vec<U128>) {
if self.timeout_actions.len() == 0 {
return (false, Vec::new());
pub fn has_timeout_actions(&self) -> Option<Vec<U128>> {
if self.timeout_actions.is_empty() {
None
} else {
let block_ts = u128::from(env::block_timestamp());
let mut timeouts: Vec<U128> = self
.timeout_actions
.to_vec()
.iter()
.map(|(k, _)| U128::from(*k))
.collect();
timeouts.retain(|t| t.0 < block_ts);
self.timeout_actions.floor_key(&block_ts).map(|_| timeouts)
}
let block_ts = u128::from(env::block_timestamp());
let key = self.timeout_actions.floor_key(&block_ts);
let mut timeouts: Vec<U128> = self
.timeout_actions
.to_vec()
.iter()
.map(|(k, _)| U128::from(*k))
.collect();
timeouts.retain(|t| t.0 < block_ts);
(key.is_some(), timeouts)
}

// TODO: Validate if this can be "trusted" to be called as expected, otherwise deprecate.
Expand All @@ -298,7 +298,7 @@ impl Contract {
.cadence_actions
.get(&cadence)
.expect("No actions to execute");
self.call_action(action.clone());
self.call_action(action);
}

/// Called by croncat trigger
Expand All @@ -307,32 +307,30 @@ impl Contract {
/// near call treasury.testnet call_timeout_actions --accountId manager_v1.croncat.testnet
/// ```
pub fn call_timeout_actions(&mut self) {
let (has, keys) = self.has_timeout_actions();
assert_eq!(has, true, "No actions to execute");
let mut actions_total = 0;
let max_chunks = 10;

// Attempt to process a total of 10 actions, packing from one or more queues
for key in keys.iter() {
if actions_total > max_chunks {
break;
}

// Get a subset of the queue based on the key
if let Some(tmp_queue) = self.timeout_actions.get(&key.0) {
let mut subset = tmp_queue;
let queue = subset.split_off(max_chunks - actions_total);

// update storage removing the subset we will process
self.timeout_actions.insert(&key.0, &queue);

// iterate the subset to process all actions
for action in subset.iter() {
self.call_action(action.clone());
}
}

actions_total += 1;
if let Some(keys) = self.has_timeout_actions() {
let max_chunks = 10;

// Attempt to process a total of 10 actions, packing from one or more queues
keys.iter()
.enumerate()
.take(max_chunks)
.for_each(|(actions_total, key)| {
// Get a subset of the queue based on the key
if let Some(tmp_queue) = self.timeout_actions.get(&key.0) {
let mut subset = tmp_queue;
let queue = subset.split_off(max_chunks - actions_total);

// update storage removing the subset we will process
self.timeout_actions.insert(&key.0, &queue);

// iterate the subset to process all actions
for action in subset.iter() {
self.call_action(action.clone());
}
}
});
} else {
panic!("No actions to execute");
}
}

Expand Down Expand Up @@ -408,12 +406,14 @@ impl Contract {
) {
// Compute the amount: whole number or percent into whole number
// NOTE: does not support percentile including staked balance, you should unstake if needed first before doing percentile payments
let final_amount = amount.unwrap_or(U128::from(
(U256::from(amount_percentile.unwrap_or(U128::from(0)).0)
* U256::from(env::account_balance())
/ U256::from(100))
.as_u128(),
));
let final_amount = amount.unwrap_or_else(|| {
U128::from(
(U256::from(amount_percentile.map(|x| x.0).unwrap_or(0))
* U256::from(env::account_balance())
/ U256::from(100))
.as_u128(),
)
});

// make the transfer
self.action_transfer(&token_id, &receiver_id, final_amount, msg);
Expand Down
2 changes: 1 addition & 1 deletion treasury/src/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ impl Contract {
self.assert_owner();

// Check approved accounts if any are specified, otherwise allow any
if self.approved_accounts_payable.len() > 0 {
if !self.approved_accounts_payable.is_empty() {
assert!(
self.approved_accounts_payable.contains(&receiver_id),
"Account restricted, needs approval"
Expand Down
72 changes: 41 additions & 31 deletions treasury/src/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl Contract {
start_block: 0, // 0 indicates that the staking has not started yet
withdraw_epoch: None,
withdraw_balance: None,
withdraw_function: withdraw_function.unwrap_or("withdraw_all".to_string()),
withdraw_function: withdraw_function.unwrap_or_else(|| "withdraw_all".to_string()),
liquid_unstake_function,
yield_function,
},
Expand Down Expand Up @@ -145,23 +145,25 @@ impl Contract {
/// near view treasury.testnet has_delegation_to_withdraw
/// ```
pub fn has_delegation_to_withdraw(&self) -> external::CroncatTriggerResponse {
let mut ret: Vec<AccountId> = Vec::new();
let mut has_withdraw = false;

// Return all data within range
let keys = self.stake_pending_delegations.keys_as_vector();
for pool_account_id in keys.iter() {
if let Some(delegation) = self.stake_pending_delegations.get(&pool_account_id) {
// Check if any of the pending delegations have a withdraw epoch older than THIS epoch
if delegation.withdraw_epoch.unwrap_or(env::epoch_height()) < env::epoch_height()
&& delegation.withdraw_balance.unwrap_or(0) > 0
{
has_withdraw = true;
}
let (ret, delegations): (Vec<AccountId>, Vec<StakeDelegation>) = self
.stake_pending_delegations
.keys_as_vector()
.iter()
.filter_map(|pool_account_id| {
self.stake_pending_delegations
.get(&pool_account_id)
.map(|delegation| (pool_account_id, delegation))
})
.unzip();

let has_withdraw = delegations.iter().any(|delegation| {
delegation
.withdraw_epoch
.map(|x| x < env::epoch_height())
.unwrap_or(false)
&& delegation.withdraw_balance.map(|x| x > 0).unwrap_or(false)
});

ret.push(pool_account_id);
}
}
(
has_withdraw,
Base64VecU8::from(serde_json::ser::to_vec(&ret).expect("Could not serialize")),
Expand Down Expand Up @@ -240,10 +242,18 @@ impl Contract {
);
}

return (
(
false,
Base64VecU8::from(serde_json::ser::to_vec(&vec![U128::from(liquid_actual), U128::from(liquid_ideal), U128::from(liquid_deviation), U128::from(liquid_extreme_deviation)]).expect("Could not serialize"))
);
Base64VecU8::from(
serde_json::ser::to_vec(&vec![
U128::from(liquid_actual),
U128::from(liquid_ideal),
U128::from(liquid_deviation),
U128::from(liquid_extreme_deviation),
])
.expect("Could not serialize"),
),
)
}

/// Check staking threshold for eval
Expand Down Expand Up @@ -303,7 +313,7 @@ impl Contract {
));
let pool = self
.stake_delegations
.get(&pool_id.clone())
.get(&pool_id)
.expect("No delegation found for pool");
// If pool supports liquid unstaking, otherwise go to regular
if pool.liquid_unstake_function.is_some() {
Expand Down Expand Up @@ -348,8 +358,7 @@ impl Contract {
stake_amount = env::attached_deposit();
} else {
assert!(
u128::from(env::account_balance())
.saturating_sub(amount.unwrap_or(U128::from(0)).0)
env::account_balance().saturating_sub(amount.map(|x| x.0).unwrap_or(0))
> MIN_BALANCE_FOR_STORAGE,
"Account Balance Under Minimum Balance"
);
Expand Down Expand Up @@ -510,7 +519,7 @@ impl Contract {

// Update our local balance values, so we know whats in process of long-form unstaking
let mut delegation = pool_delegation.unwrap();
let withdraw_balance = amount.unwrap_or(U128::from(0)).0;
let withdraw_balance = amount.map(|x| x.0).unwrap_or(0);
delegation.withdraw_epoch = Some(env::epoch_height() + 4);
delegation.withdraw_balance = Some(withdraw_balance);
self.stake_pending_delegations
Expand All @@ -519,7 +528,7 @@ impl Contract {
// Lastly, make the cross-contract call to DO the unstaking :D
let p = env::promise_create(
pool_account_id.clone(),
&unstake_function,
unstake_function,
json!({
"amount": amount,
})
Expand Down Expand Up @@ -733,18 +742,19 @@ impl Contract {
// If no amount specified, simply unstake all st_near
// IF amount, compare to use the maximum unstakable that matches user amounts
// TODO: This is always returning with less NEAR than expected because of fees being taken out, need to add fee to amount so ratio can include fee
if amount.is_some() {
if let Some(amount) = amount {
// Get amount ratio, then desired st_near from ratio
// limit to maximum st_near balance
let denominator = 100;
let desired_amount = u128::from(amount.unwrap().0).saturating_mul(denominator);
let desired_amount = amount.0.saturating_mul(denominator);
let ratio = desired_amount.div_euclid(pool_min_expected_near.0);
let st_unstake_amount =
u128::from(st_near.0.saturating_mul(ratio)).div_euclid(denominator);
let st_unstake_amount = st_near.0.saturating_mul(ratio).div_euclid(denominator);
if st_near.0 > st_unstake_amount {
st_near_to_burn = U128::from(st_unstake_amount);
pool_min_expected_near = U128::from(
u128::from(pool_min_expected_near.0.saturating_mul(ratio))
pool_min_expected_near
.0
.saturating_mul(ratio)
.div_euclid(denominator),
);
}
Expand All @@ -756,7 +766,7 @@ impl Contract {
.get(&pool_account_id)
.expect("Delegation doesnt exist");
let p1 = env::promise_create(
pool_account_id.clone(),
pool_account_id,
&delegation.liquid_unstake_function.unwrap(),
json!({
"st_near_to_burn": st_near_to_burn,
Expand Down
2 changes: 1 addition & 1 deletion treasury/src/views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Contract {
self.owner_id.to_string(),
self.croncat_id
.clone()
.unwrap_or(AccountId::from_str("no_croncat_account").unwrap())
.unwrap_or_else(|| AccountId::from_str("no_croncat_account").unwrap())
.to_string(),
self.stake_threshold.clone(),
)
Expand Down