Skip to content

Commit e75b350

Browse files
committed
Merge remote-tracking branch 'main' into dev
2 parents b9f14a6 + 954a248 commit e75b350

File tree

9 files changed

+75
-129
lines changed

9 files changed

+75
-129
lines changed

pallets/emission0/src/distribute.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,7 @@ pub fn get_total_emission_per_block<T: Config>() -> BalanceOf<T> {
7474
}
7575

7676
let interval = T::HalvingInterval::get();
77-
let halving_count = total_issuance
78-
.checked_div(interval.get())
79-
.unwrap_or_default();
77+
let halving_count = total_issuance.checked_div(interval.get()).unwrap_or(0);
8078
let emission = T::BlockEmission::get() >> halving_count;
8179

8280
let not_recycled =

pallets/torus0/src/agent.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,9 +148,10 @@ pub fn unregister<T: crate::Config>(agent_key: AccountIdOf<T>) -> DispatchResult
148148
namespace_path,
149149
)?;
150150

151-
crate::Agents::<T>::remove(&agent_key);
152151
crate::stake::clear_key::<T>(&agent_key)?;
153152

153+
crate::Agents::<T>::remove(&agent_key);
154+
154155
crate::Pallet::<T>::deposit_event(crate::Event::<T>::AgentUnregistered(agent_key));
155156

156157
Ok(())

pallets/torus0/src/migrations.rs

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use polkadot_sdk::frame_support::{
44

55
use crate::{Config, Pallet};
66

7-
pub mod v3 {
7+
pub mod v4 {
88
use super::*;
99
use crate::{Agent, Agents};
1010
use scale_info::prelude::vec::Vec;
@@ -35,9 +35,9 @@ pub mod v3 {
3535
StorageMap<crate::Pallet<T>, Identity, AccountIdOf<T>, Agent<T>>;
3636
}
3737

38-
pub type Migration<T, W> = VersionedMigration<2, 3, MigrateToV3<T>, Pallet<T>, W>;
39-
pub struct MigrateToV3<T>(core::marker::PhantomData<T>);
40-
impl<T: Config> UncheckedOnRuntimeUpgrade for MigrateToV3<T> {
38+
pub type Migration<T, W> = VersionedMigration<3, 4, MigrateToV4<T>, Pallet<T>, W>;
39+
pub struct MigrateToV4<T>(core::marker::PhantomData<T>);
40+
impl<T: Config> UncheckedOnRuntimeUpgrade for MigrateToV4<T> {
4141
fn on_runtime_upgrade() -> Weight {
4242
let old_agents = storage::Agents::<T>::iter().collect::<Vec<_>>();
4343
let _ = storage::Agents::<T>::clear(u32::MAX, None);
@@ -63,24 +63,6 @@ pub mod v3 {
6363
}
6464
}
6565

66-
pub mod v4 {
67-
use polkadot_sdk::{
68-
frame_support::{migrations::VersionedMigration, traits::UncheckedOnRuntimeUpgrade},
69-
sp_weights::Weight,
70-
};
71-
72-
use crate::{Config, Pallet};
73-
74-
pub type Migration<T, W> = VersionedMigration<3, 4, MigrateToV4<T>, Pallet<T>, W>;
75-
pub struct MigrateToV4<T>(core::marker::PhantomData<T>);
76-
77-
impl<T: Config> UncheckedOnRuntimeUpgrade for MigrateToV4<T> {
78-
fn on_runtime_upgrade() -> Weight {
79-
Weight::zero()
80-
}
81-
}
82-
}
83-
8466
pub mod v5 {
8567
use pallet_torus0_api::{NamespacePath, NAMESPACE_AGENT_PREFIX};
8668
use polkadot_sdk::{

pallets/torus0/src/stake.rs

Lines changed: 40 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ use polkadot_sdk::{
22
frame_support::{
33
dispatch::DispatchResult,
44
ensure,
5-
traits::{Currency, ExistenceRequirement, WithdrawReasons},
5+
traits::{Currency, ExistenceRequirement, Imbalance, WithdrawReasons},
66
},
77
sp_std::{collections::btree_map::BTreeMap, vec::Vec},
8-
sp_tracing::error,
98
};
109

11-
use crate::{agent, AccountIdOf, BalanceOf};
10+
use crate::agent;
11+
use crate::{AccountIdOf, BalanceOf};
1212

1313
/// Stakes `amount` tokens from `staker` to `staked` by withdrawing the tokens
1414
/// and adding them to the [`crate::StakingTo`] and [`crate::StakedBy`] maps.
@@ -51,11 +51,6 @@ pub fn remove_stake<T: crate::Config>(
5151
staked: AccountIdOf<T>,
5252
amount: BalanceOf<T>,
5353
) -> DispatchResult {
54-
ensure!(
55-
amount >= crate::MinAllowedStake::<T>::get(),
56-
crate::Error::<T>::StakeTooSmall
57-
);
58-
5954
ensure!(
6055
agent::exists::<T>(&staked),
6156
crate::Error::<T>::AgentDoesNotExist
@@ -66,21 +61,44 @@ pub fn remove_stake<T: crate::Config>(
6661
crate::Error::<T>::NotEnoughStakeToWithdraw
6762
);
6863

69-
crate::StakingTo::<T>::mutate(&staker, &staked, |stake| {
70-
*stake = Some(stake.unwrap_or(0).saturating_sub(amount))
71-
});
72-
73-
crate::StakedBy::<T>::mutate(&staked, &staker, |stake| {
74-
*stake = Some(stake.unwrap_or(0).saturating_sub(amount))
75-
});
64+
remove_stake0::<T>(staker, staked, amount, true);
7665

77-
crate::TotalStake::<T>::mutate(|total_stake| *total_stake = total_stake.saturating_sub(amount));
66+
Ok(())
67+
}
7868

79-
let _ = <T as crate::Config>::Currency::deposit_creating(&staker, amount);
69+
fn remove_stake0<T: crate::Config>(
70+
staker: AccountIdOf<T>,
71+
staked: AccountIdOf<T>,
72+
amount: BalanceOf<T>,
73+
keep: bool,
74+
) {
75+
let Some(stake) = crate::StakingTo::<T>::get(&staker, &staked) else {
76+
return;
77+
};
78+
79+
let mut stake = T::Currency::issue(stake);
80+
let retrieved = stake.extract(amount);
81+
82+
let new_stake = if keep || stake.peek() > 0 {
83+
Some(stake.peek())
84+
} else {
85+
None
86+
};
87+
88+
crate::StakingTo::<T>::set(&staker, &staked, new_stake);
89+
crate::StakedBy::<T>::set(&staked, &staker, new_stake);
90+
crate::TotalStake::<T>::mutate(|total_stake| {
91+
*total_stake = total_stake.saturating_sub(retrieved.peek())
92+
});
8093

81-
crate::Pallet::<T>::deposit_event(crate::Event::<T>::StakeRemoved(staker, staked, amount));
94+
let retrieved_value = retrieved.peek();
95+
<T as crate::Config>::Currency::resolve_creating(&staker, retrieved);
8296

83-
Ok(())
97+
crate::Pallet::<T>::deposit_event(crate::Event::<T>::StakeRemoved(
98+
staker,
99+
staked,
100+
retrieved_value,
101+
));
84102
}
85103

86104
/// Transfers stake from an account to another (see [`remove_stake`],
@@ -99,16 +117,10 @@ pub fn transfer_stake<T: crate::Config>(
99117
/// Usually called when de-registering an agent, removes all stakes on a given
100118
/// key.
101119
pub(crate) fn clear_key<T: crate::Config>(key: &AccountIdOf<T>) -> DispatchResult {
102-
for (staker, staked, amount) in crate::StakingTo::<T>::iter() {
120+
let stakes: Vec<_> = crate::StakingTo::<T>::iter().collect();
121+
for (staker, staked, amount) in stakes {
103122
if &staker == key || &staked == key {
104-
crate::StakingTo::<T>::remove(&staker, &staked);
105-
crate::StakedBy::<T>::remove(&staked, &staker);
106-
if let Err(err) = remove_stake::<T>(staker.clone(), staked.clone(), amount) {
107-
error!(
108-
"could not remove stake from {:?} to {:?}: {err:?}",
109-
staker, staked
110-
)
111-
}
123+
remove_stake0::<T>(staker, staked, amount, false);
112124
}
113125
}
114126

pallets/torus0/tests/stake.rs

Lines changed: 18 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use pallet_torus0::{Error, MinAllowedStake, StakedBy, StakingTo, TotalStake};
22
use polkadot_sdk::frame_support::{assert_err, traits::Currency};
3-
use test_utils::{assert_ok, get_origin, pallet_governance, Balances, Test};
3+
use test_utils::{as_tors, assert_ok, get_origin, pallet_governance, Balances, Test};
44

55
#[test]
66
fn add_stake_correctly() {
@@ -192,94 +192,51 @@ fn remove_stake_correctly() {
192192
}
193193

194194
#[test]
195-
fn remove_stake_with_less_than_required_amount() {
195+
fn remove_stake_with_unregistered_agent() {
196196
test_utils::new_test_ext().execute_with(|| {
197197
let from = 0;
198198
let to = 1;
199-
let stake_to_add_and_remove = MinAllowedStake::<Test>::get();
200-
let total_balance = stake_to_add_and_remove * 2;
199+
200+
let stake = as_tors(500);
201+
let total_balance = stake * 2;
201202

202203
assert_ok!(pallet_governance::whitelist::add_to_whitelist::<Test>(to));
203204
assert_ok!(pallet_torus0::Pallet::<Test>::register_agent(
204205
get_origin(to),
205206
to,
206-
"to".as_bytes().to_vec(),
207-
"to://idk".as_bytes().to_vec(),
208-
"idk".as_bytes().to_vec()
207+
b"to".to_vec(),
208+
b"to://idk".to_vec(),
209+
b"idk".to_vec()
209210
));
210211

211212
let _ = Balances::deposit_creating(&from, total_balance);
212-
assert_eq!(Balances::total_balance(&to), 0);
213213

214+
assert_eq!(Balances::total_balance(&from), total_balance);
215+
assert_eq!(Balances::total_balance(&to), 0);
214216
assert_ok!(pallet_torus0::Pallet::<Test>::add_stake(
215217
get_origin(from),
216218
to,
217-
stake_to_add_and_remove
219+
stake,
218220
));
219221

220-
assert_err!(
221-
pallet_torus0::Pallet::<Test>::remove_stake(
222-
get_origin(from),
223-
to,
224-
stake_to_add_and_remove - 1
225-
),
226-
Error::<Test>::StakeTooSmall,
227-
);
222+
assert_eq!(Balances::total_balance(&from), total_balance / 2);
228223

229-
assert_eq!(Balances::total_balance(&from), stake_to_add_and_remove);
230-
assert_eq!(
231-
StakingTo::<Test>::get(from, to),
232-
Some(stake_to_add_and_remove)
233-
);
234-
assert_eq!(
235-
StakedBy::<Test>::get(to, from),
236-
Some(stake_to_add_and_remove)
237-
);
238-
assert_eq!(TotalStake::<Test>::get(), stake_to_add_and_remove);
239-
});
240-
}
224+
assert_eq!(TotalStake::<Test>::get(), stake);
225+
assert_eq!(StakingTo::<Test>::get(from, to), Some(stake));
226+
assert_eq!(StakedBy::<Test>::get(to, from), Some(stake));
241227

242-
#[test]
243-
fn remove_stake_with_unregistered_agent() {
244-
test_utils::new_test_ext().execute_with(|| {
245-
let from = 0;
246-
let to = 1;
247-
let stake_to_add_and_remove = MinAllowedStake::<Test>::get();
248-
let total_balance = stake_to_add_and_remove * 2;
249-
250-
assert_ok!(pallet_governance::whitelist::add_to_whitelist::<Test>(to));
251-
assert_ok!(pallet_torus0::Pallet::<Test>::register_agent(
252-
get_origin(to),
253-
to,
254-
"to".as_bytes().to_vec(),
255-
"to://idk".as_bytes().to_vec(),
256-
"idk".as_bytes().to_vec()
257-
));
258-
259-
let _ = Balances::deposit_creating(&from, total_balance);
260-
261-
assert_eq!(Balances::total_balance(&to), 0);
262-
assert_ok!(pallet_torus0::Pallet::<Test>::add_stake(
263-
get_origin(from),
264-
to,
265-
stake_to_add_and_remove,
266-
));
267228
assert_ok!(pallet_torus0::Pallet::<Test>::unregister_agent(get_origin(
268229
to
269230
)));
270231

271232
assert_err!(
272-
pallet_torus0::Pallet::<Test>::remove_stake(
273-
get_origin(from),
274-
to,
275-
stake_to_add_and_remove
276-
),
233+
pallet_torus0::Pallet::<Test>::remove_stake(get_origin(from), to, stake),
277234
Error::<Test>::AgentDoesNotExist,
278235
);
279236

280-
assert_eq!(Balances::total_balance(&from), stake_to_add_and_remove);
237+
assert_eq!(Balances::total_balance(&from), total_balance);
281238
assert_eq!(StakingTo::<Test>::get(from, to), None);
282239
assert_eq!(StakedBy::<Test>::get(to, from), None);
283-
assert_eq!(TotalStake::<Test>::get(), stake_to_add_and_remove);
240+
assert_eq!(TotalStake::<Test>::get(), 0);
284241
});
285242
}

runtime/src/configs.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,11 @@ impl pallet_sudo::Config for Runtime {
137137

138138
parameter_types! {
139139
// Base: 1 token + (88 bytes * 0.01 token)
140-
pub const DepositBase: Balance = 10u128.saturating_pow(TOKEN_DECIMALS) // 1 token
141-
.saturating_add(88u128.saturating_mul(10u128.saturating_pow(TOKEN_DECIMALS - 2))); // 0.01 token per byte
140+
pub const DepositBase: Balance = 10u128.saturating_pow(TOKEN_DECIMALS) // 1 token
141+
.saturating_add(88u128.saturating_mul(10u128.saturating_pow(TOKEN_DECIMALS.saturating_sub(2)))); // 0.01 token per byte
142142
// Factor: (32 bytes * 0.01 token)
143143
pub const DepositFactor: Balance =
144-
32u128.saturating_mul(10u128.saturating_pow(TOKEN_DECIMALS - 2)); // 0.01 token per byte
144+
32u128.saturating_mul(10u128.saturating_pow(TOKEN_DECIMALS.saturating_sub(2))); // 0.01 token per byte
145145
}
146146

147147
impl pallet_multisig::Config for Runtime {

runtime/src/configs/eth.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,10 @@ impl<F: FindAuthor<u32>> FindAuthor<H160> for FindAuthorTruncated<F> {
3232
where
3333
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
3434
{
35-
let authority_id = F::find_author(digests).and_then(|author_index| {
36-
pallet_aura::Authorities::<Runtime>::get()
37-
.get(author_index as usize)
38-
.cloned()
39-
})?;
40-
41-
authority_id.to_raw_vec().get(4..24).map(H160::from_slice)
35+
use pallet_aura::Authorities;
36+
F::find_author(digests)
37+
.and_then(|index| Authorities::<Runtime>::get().get(index as usize).cloned())
38+
.and_then(|id| id.to_raw_vec().get(4..24).map(H160::from_slice))
4239
}
4340
}
4441

@@ -63,7 +60,7 @@ pub const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_
6360

6461
parameter_types! {
6562
pub BlockGasLimit: U256
66-
= U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
63+
= U256::from((NORMAL_DISPATCH_RATIO.deconstruct() as u64).saturating_mul(MAXIMUM_BLOCK_WEIGHT.ref_time()).checked_div(WEIGHT_PER_GAS).unwrap_or(0));
6764
pub const GasLimitPovSizeRatio: u64 = 16;
6865
/// The amount of gas per storage (in bytes): BLOCK_GAS_LIMIT / BLOCK_STORAGE_LIMIT
6966
/// The current definition of BLOCK_STORAGE_LIMIT is 160 KB, resulting in a value of 366.

runtime/src/lib.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
3838
spec_name: create_runtime_str!("torus-runtime"),
3939
impl_name: create_runtime_str!("torus-runtime"),
4040
authoring_version: 1,
41-
spec_version: 20,
41+
spec_version: 21,
4242
impl_version: 1,
4343
apis: apis::RUNTIME_API_VERSIONS,
4444
transaction_version: 1,
@@ -90,7 +90,6 @@ type Migrations = (
9090
pallet_permission0::migrations::v2::Migration<Runtime, RocksDbWeight>,
9191
pallet_permission0::migrations::v3::Migration<Runtime, RocksDbWeight>,
9292
pallet_emission0::migrations::v2::Migration<Runtime, RocksDbWeight>,
93-
pallet_torus0::migrations::v3::Migration<Runtime, RocksDbWeight>,
9493
pallet_torus0::migrations::v4::Migration<Runtime, RocksDbWeight>,
9594
pallet_torus0::migrations::v5::Migration<Runtime, RocksDbWeight>,
9695
);

test-utils/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#![allow(non_camel_case_types)]
1+
#![allow(non_camel_case_types, unexpected_cfgs)]
22

33
use std::{cell::RefCell, num::NonZeroU128};
44

0 commit comments

Comments
 (0)