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

feat(vara,gear-bank): Split gas and fees to author/treasury #3652

Merged
merged 42 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
4c601db
feat(vara): Split fees 50/50, author/treasury
ukint-vs Jan 10, 2024
6003d82
resolve comments
ukint-vs Jan 11, 2024
d08dabb
Merge branch 'master' into vs/treasury-fee
ukint-vs Jan 23, 2024
e51ce6e
Split gas fees in gear-bank
ukint-vs Jan 30, 2024
96c14f3
update mocks
ukint-vs Jan 30, 2024
bc4f5c1
Merge branch 'master' into vs/treasury-fee
ukint-vs Jan 30, 2024
9313060
fix split
ukint-vs Feb 1, 2024
3f4c701
don't split gas fee in tests
ukint-vs Feb 1, 2024
5d4f7ee
Assert 50% in tests
ukint-vs Feb 3, 2024
ca9c384
correct calculations
ukint-vs Feb 7, 2024
9a695dc
Fix gas fee split, fix test
ukint-vs Feb 11, 2024
c43ce6f
fmt
ukint-vs Feb 11, 2024
bce92de
fix gcli test
ukint-vs Feb 26, 2024
0118a82
fmt
ukint-vs Feb 27, 2024
9059f96
Merge branch 'master' into vs/treasury-fee
ukint-vs Feb 27, 2024
051fe38
Update gear-builtin mocks
ukint-vs Feb 27, 2024
667259c
Merge branch 'master' into vs/treasury-fee
ukint-vs Feb 28, 2024
9ece8ba
fix and rename gas split
ukint-vs Mar 1, 2024
368ca07
100% gas and fee goes to the block author
ukint-vs Mar 1, 2024
163105a
rm comment
ukint-vs Mar 1, 2024
eb9845a
Merge branch 'master' into vs/treasury-fee
ukint-vs Apr 8, 2024
13488c9
Make constants
ukint-vs Apr 8, 2024
66e78d1
Use Option inside split fee param
ukint-vs Apr 9, 2024
3897347
clippy
ukint-vs Apr 9, 2024
50b0bf9
Merge branch 'master' into vs/treasury-fee
ukint-vs May 28, 2024
ae458a9
fmt
ukint-vs May 28, 2024
72ff667
Make tx fee ratio available in gear-bank storage
ukint-vs May 29, 2024
b726e86
Merge branch 'master' into vs/treasury-fee
ukint-vs Jul 7, 2024
f50f715
move gas fee split to on_finalize hook
ukint-vs Jul 7, 2024
563db85
fix test
ukint-vs Jul 7, 2024
95a296e
clippy
ukint-vs Jul 7, 2024
b108703
get percent from config
ukint-vs Jul 8, 2024
81fe96a
Merge branch 'master' into vs/treasury-fee
ukint-vs Jul 16, 2024
64d44b9
add note
ukint-vs Jul 16, 2024
84c0c90
Merge branch 'master' into vs/treasury-fee
ukint-vs Aug 1, 2024
0fbd33e
Merge branch 'master' into vs/treasury-fee
ukint-vs Aug 14, 2024
43706b3
Merge remote-tracking branch 'origin/master' into vs/treasury-fee
ukint-vs Aug 14, 2024
eb2ef05
update tests
ukint-vs Aug 14, 2024
916552d
rename
ukint-vs Aug 21, 2024
80e59a4
Merge remote-tracking branch 'origin/master' into vs/treasury-fee
ukint-vs Aug 21, 2024
c6153ce
update subxt
ukint-vs Aug 22, 2024
a2e924d
fix .lock
breathx Aug 22, 2024
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 27 additions & 5 deletions pallets/gear-bank/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ macro_rules! impl_config {
type Currency = Balances;
type BankAddress = BankAddress;
type GasMultiplier = GasMultiplier;
type SplitGas = SplitGas;
ukint-vs marked this conversation as resolved.
Show resolved Hide resolved
type SplitTxFeeRatio = SplitTxFeeRatio;
}
};
}
Expand Down Expand Up @@ -66,7 +68,7 @@ pub mod pallet {
use pallet_authorship::Pallet as Authorship;
use parity_scale_codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_runtime::traits::Zero;
use sp_runtime::{traits::Zero, Perbill};

// Funds pallet struct itself.
#[pallet::pallet]
Expand All @@ -86,6 +88,11 @@ pub mod pallet {
#[pallet::constant]
/// Gas price converter.
type GasMultiplier: Get<GasMultiplier<Self>>;

type SplitGas: Get<Option<(Perbill, AccountIdOf<Self>)>>;

/// The ratio of how much of the tx fees goes to the treasury
type SplitTxFeeRatio: Get<Option<u32>>;
}

// Funds pallets error.
Expand Down Expand Up @@ -296,10 +303,25 @@ pub mod pallet {
Self::ensure_bank_can_transfer(value)?;

OnFinalizeValue::<T>::mutate(|v| *v = v.saturating_add(value));
OnFinalizeTransfers::<T>::mutate(account_id, |v| {
let inner = v.get_or_insert(Zero::zero());
*inner = inner.saturating_add(value);
});
if let Some((gas_split, split_dest)) = T::SplitGas::get() {
ukint-vs marked this conversation as resolved.
Show resolved Hide resolved
// split value by `SplitGas`
let to_split = gas_split.mul_floor(value);
let to_user = value - to_split;

OnFinalizeTransfers::<T>::mutate(account_id, |v| {
let inner = v.get_or_insert(Zero::zero());
*inner = inner.saturating_add(to_user);
});
OnFinalizeTransfers::<T>::mutate(split_dest, |v| {
let inner = v.get_or_insert(Zero::zero());
*inner = inner.saturating_add(to_split);
});
} else {
OnFinalizeTransfers::<T>::mutate(account_id, |v| {
let inner = v.get_or_insert(Zero::zero());
*inner = inner.saturating_add(value);
});
}

Ok(())
}
Expand Down
7 changes: 5 additions & 2 deletions pallets/gear-bank/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ use frame_support::{
construct_runtime, parameter_types,
traits::{ConstU32, FindAuthor},
weights::constants::RocksDbWeight,
PalletId,
};
use primitive_types::H256;
use sp_io::TestExternalities;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
traits::{AccountIdConversion, BlakeTwo256, IdentityLookup},
BuildStorage, Perbill,
};

pub type AccountId = u8;
Expand Down Expand Up @@ -64,6 +65,8 @@ parameter_types! {
pub const GasMultiplier: common::GasMultiplier<Balance, u64> = common::GasMultiplier::ValuePerGas(VALUE_PER_GAS);
pub const BlockHashCount: BlockNumber = 250;
pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
pub SplitGas: Option<(Perbill, AccountId)> = Some((Perbill::from_percent(50), PalletId(*b"py/trsry").into_account_truncating()));
pub SplitTxFeeRatio: Option<u32> = None;
}

construct_runtime!(
Expand Down
16 changes: 13 additions & 3 deletions pallets/gear-bank/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

use crate::{mock::*, GasMultiplier, OnFinalizeValue, UnusedValue, *};
use frame_support::{assert_noop, assert_ok, traits::Hooks};
use sp_runtime::{traits::Zero, StateVersion};
use sp_runtime::{traits::Zero, Perbill, StateVersion};
use utils::*;

#[test]
Expand Down Expand Up @@ -499,7 +499,11 @@ fn spend_gas_all_balance_validator_account_deleted() {

assert_bank_balance(0, 0);

assert_balance(&BLOCK_AUTHOR, gas_price(GAS_AMOUNT));
// mul ceil GAS_AMOUNT because of gas fee split 50%
assert_balance(
&BLOCK_AUTHOR,
Perbill::from_percent(50).mul_ceil(gas_price(GAS_AMOUNT)),
);

assert_alice_dec(gas_price(GAS_AMOUNT));
assert_gas_value(&ALICE, 0, 0);
Expand Down Expand Up @@ -1552,6 +1556,8 @@ fn spend_gas_on_finalize_single_user() {
}

mod utils {
use sp_runtime::Perbill;

use super::*;

// For some reason `assert_noop!` doesnt work for the pallet fns.
Expand Down Expand Up @@ -1621,7 +1627,11 @@ mod utils {
// Asserts block author balance inc.
#[track_caller]
pub fn assert_block_author_inc(diff: Balance) {
assert_balance(&BLOCK_AUTHOR, EXISTENTIAL_DEPOSIT + diff)
// mul ceil diff because of gas fee split 50%
assert_balance(
&BLOCK_AUTHOR,
EXISTENTIAL_DEPOSIT + Perbill::from_percent(50).mul_ceil(diff),
ukint-vs marked this conversation as resolved.
Show resolved Hide resolved
)
}

// Asserts Charlie balance inc.
Expand Down
4 changes: 3 additions & 1 deletion pallets/gear-builtin/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use gear_core::{
use sp_core::H256;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
BuildStorage, Perbill,
};
use sp_std::convert::{TryFrom, TryInto};

Expand Down Expand Up @@ -108,6 +108,8 @@ parameter_types! {
pub const PerformanceMultiplier: u32 = 100;
pub const BankAddress: AccountId = 15082001;
pub const GasMultiplier: common::GasMultiplier<Balance, u64> = common::GasMultiplier::ValuePerGas(25);
pub SplitGas: Option<(Perbill, AccountId)> = None;
pub SplitTxFeeRatio: Option<u32> = None;
}

pallet_gear_bank::impl_config!(Test);
Expand Down
4 changes: 3 additions & 1 deletion pallets/gear-builtin/src/tests/bad_builtin_ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use gear_core::{
use sp_core::H256;
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
BuildStorage, Perbill,
};
use sp_std::convert::{TryFrom, TryInto};

Expand Down Expand Up @@ -80,6 +80,8 @@ parameter_types! {
pub const PerformanceMultiplier: u32 = 100;
pub const BankAddress: AccountId = 15082001;
pub const GasMultiplier: common::GasMultiplier<Balance, u64> = common::GasMultiplier::ValuePerGas(25);
pub SplitGas: Option<(Perbill, AccountId)> = None;
pub SplitTxFeeRatio: Option<u32> = None;
}

pallet_gear_bank::impl_config!(Test);
Expand Down
4 changes: 3 additions & 1 deletion pallets/gear-debug/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use primitive_types::H256;
use sp_core::ConstBool;
use sp_runtime::{
traits::{BlakeTwo256, ConstU64, IdentityLookup},
BuildStorage,
BuildStorage, Perbill,
};
use sp_std::convert::{TryFrom, TryInto};

Expand Down Expand Up @@ -70,6 +70,8 @@ parameter_types! {
pub ResumeSessionDuration: BlockNumber = 1_000;
pub const BankAddress: AccountId = 15082001;
pub const GasMultiplier: common::GasMultiplier<Balance, u64> = common::GasMultiplier::ValuePerGas(25);
pub SplitGas: Option<(Perbill, AccountId)> = None;
pub SplitTxFeeRatio: Option<u32> = None;
pub ReserveThreshold: BlockNumber = 1;
}

Expand Down
4 changes: 3 additions & 1 deletion pallets/gear-scheduler/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use pallet_gear::GasAllowanceOf;
use sp_core::{ConstBool, H256};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
BuildStorage, Perbill,
};

use sp_std::convert::{TryFrom, TryInto};
Expand Down Expand Up @@ -94,6 +94,8 @@ parameter_types! {
pub ResumeSessionDuration: BlockNumber = 1_000;
pub const BankAddress: AccountId = 15082001;
pub const GasMultiplier: common::GasMultiplier<Balance, u64> = common::GasMultiplier::ValuePerGas(25);
pub SplitGas: Option<(Perbill, AccountId)> = None;
pub SplitTxFeeRatio: Option<u32> = None;
}

// Build genesis storage according to the mock runtime.
Expand Down
4 changes: 3 additions & 1 deletion pallets/gear/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use frame_system::{self as system, limits::BlockWeights, mocking, pallet_prelude
use sp_core::{ConstU8, H256};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage,
BuildStorage, Perbill,
};
use sp_std::{
cell::RefCell,
Expand Down Expand Up @@ -161,6 +161,8 @@ impl Drop for DynamicScheduleReset {
parameter_types! {
pub const BankAddress: AccountId = 15082001;
pub const GasMultiplier: common::GasMultiplier<Balance, u64> = common::GasMultiplier::ValuePerGas(25);
pub SplitGas: Option<(Perbill, AccountId)> = None;
pub SplitTxFeeRatio: Option<u32> = None;
pub const MinVoucherDuration: BlockNumber = 5;
pub const MaxVoucherDuration: BlockNumber = 100_000_000;
}
Expand Down
4 changes: 3 additions & 1 deletion pallets/payment/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use primitive_types::H256;
use sp_runtime::{
testing::TestXt,
traits::{BlakeTwo256, ConstBool, ConstU64, IdentityLookup},
BuildStorage,
BuildStorage, Perbill,
};
use sp_std::{
convert::{TryFrom, TryInto},
Expand Down Expand Up @@ -119,6 +119,8 @@ parameter_types! {
pub ResumeSessionDuration: BlockNumber = 1_000;
pub const BankAddress: AccountId = 15082001;
pub const GasMultiplier: common::GasMultiplier<Balance, u64> = common::GasMultiplier::ValuePerGas(25);
pub SplitGas: Option<(Perbill, AccountId)> = None;
pub SplitTxFeeRatio: Option<u32> = None;
}

type NegativeImbalance = <Balances as Currency<u64>>::NegativeImbalance;
Expand Down
1 change: 1 addition & 0 deletions runtime/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ frame-system.workspace = true
pallet-authorship.workspace = true
pallet-balances.workspace = true
pallet-session.workspace = true
pallet-treasury.workspace = true
sp-runtime.workspace = true
sp-std.workspace = true

Expand Down
6 changes: 6 additions & 0 deletions runtime/common/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,9 @@ pub const RENT_FREE_PERIOD_MONTH_FACTOR: BlockNumber = 6;
/// The amount of blocks on which tasks of pausing program shifted
/// in a case of disabled program rent logic, represented as a factor of weeks.
pub const RENT_DISABLED_DELTA_WEEK_FACTOR: BlockNumber = 1;

/// The percentage of the transaction fee that will go to the treasury
pub const SPLIT_TX_FEE_PERCENT: u32 = 0;

/// The percentage of the gas fee that will go to the specified destination
pub const SPLIT_GAS_PERCENT: u32 = 0;
50 changes: 42 additions & 8 deletions runtime/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ mod apis;
pub mod constants;
pub mod weights;

use sp_runtime::traits::Get;

use frame_support::{
pallet_prelude::DispatchClass,
parameter_types,
traits::{Currency, OnUnbalanced},
traits::{Currency, Imbalance, OnUnbalanced},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight},
Weight,
Expand Down Expand Up @@ -79,22 +81,54 @@ pub type NegativeImbalance<T> = <pallet_balances::Pallet<T> as Currency<
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;

/// Logic for the author to get a portion of fees.
pub struct ToAuthor<R>(sp_std::marker::PhantomData<R>);
impl<R> OnUnbalanced<NegativeImbalance<R>> for ToAuthor<R>
where
R: pallet_balances::Config + pallet_authorship::Config,
<R as frame_system::Config>::AccountId: From<AccountId>,
<R as frame_system::Config>::AccountId: Into<AccountId>,
{
fn on_nonzero_unbalanced(amount: NegativeImbalance<R>) {
if let Some(author) = <pallet_authorship::Pallet<R>>::author() {
<pallet_balances::Pallet<R>>::resolve_creating(&author, amount);
}
}
}

pub struct DealWithFees<R>(sp_std::marker::PhantomData<R>);
impl<R> OnUnbalanced<NegativeImbalance<R>> for DealWithFees<R>
where
R: pallet_balances::Config + pallet_authorship::Config,
R: pallet_balances::Config
+ pallet_treasury::Config
+ pallet_authorship::Config
+ pallet_gear_bank::Config,
pallet_treasury::Pallet<R>: OnUnbalanced<NegativeImbalance<R>>,
<R as frame_system::Config>::AccountId: From<AccountId>,
<R as frame_system::Config>::AccountId: Into<AccountId>,
{
fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance<R>>) {
use pallet_treasury::Pallet as Treasury;

if let Some(fees) = fees_then_tips.next() {
if let Some(author) = <pallet_authorship::Pallet<R>>::author() {
<pallet_balances::Pallet<R>>::resolve_creating(&author, fees);
}
if let Some(tips) = fees_then_tips.next() {
if let Some(author) = <pallet_authorship::Pallet<R>>::author() {
<pallet_balances::Pallet<R>>::resolve_creating(&author, tips);
let split_tx_fee_ratio = R::SplitTxFeeRatio::get();
if let Some(split_tx_fee_ratio) = split_tx_fee_ratio {
// for fees, SplitTxFeeRatio to treasury else to author
let (mut to_author, to_treasury) =
fees.ration(100 - split_tx_fee_ratio, split_tx_fee_ratio);
if let Some(tips) = fees_then_tips.next() {
// for tips, if any, 100% to author
tips.merge_into(&mut to_author);
}
<Treasury<R> as OnUnbalanced<_>>::on_unbalanced(to_treasury);
<ToAuthor<R> as OnUnbalanced<_>>::on_unbalanced(to_author);
} else {
let mut to_author = fees;
if let Some(tips) = fees_then_tips.next() {
// for tips, if any, 100% to author
tips.merge_into(&mut to_author);
}
<ToAuthor<R> as OnUnbalanced<_>>::on_unbalanced(to_author);
}
}
}
Expand Down
45 changes: 45 additions & 0 deletions runtime/vara/src/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,48 @@ fn slashed_proposals_back_to_treasury() {
assert_eq!(Balances::total_issuance(), initial_total_issuance);
});
}

#[test]
fn test_fees_and_tip_split() {
breathx marked this conversation as resolved.
Show resolved Hide resolved
init_logger();

let alice = AccountKeyring::Alice;
let charlie = AccountKeyring::Charlie;

ExtBuilder::default()
.initial_authorities(vec![(
alice.into(),
charlie.into(),
alice.public(),
ed25519::Pair::from_string("//Alice", None)
.unwrap()
.public(),
alice.public(),
alice.public(),
)])
.stash(STASH)
.endowment(ENDOWMENT)
.endowed_accounts(vec![])
.root(alice.into())
.build()
.execute_with(|| {
let fee = Balances::issue(10);
let tip = Balances::issue(20);

assert_eq!(
Balances::free_balance(Treasury::account_id()),
EXISTENTIAL_DEPOSIT
);
assert_eq!(Balances::free_balance(alice.to_account_id()), STASH);

DealWithFees::on_unbalanceds(vec![fee, tip].into_iter());
breathx marked this conversation as resolved.
Show resolved Hide resolved

// Author gets 100% of the tip and 100% of the fee = 30
assert_eq!(Balances::free_balance(alice.to_account_id()), STASH + 30);
// Treasury gets 0% of the fee
assert_eq!(
Balances::free_balance(Treasury::account_id()),
EXISTENTIAL_DEPOSIT
);
});
}
Loading
Loading