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(node): Modify rent reward distributions #3686

Merged
merged 35 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
d3d7a77
make funcs generic
gshep Jan 22, 2024
9b0e826
runtime with two block producers
gshep Jan 22, 2024
3240aab
add methods for rent pool info
gshep Jan 23, 2024
163559e
implement rent rewards payout
gshep Jan 23, 2024
570c264
make pre-commit
gshep Jan 23, 2024
6597890
transfer charges for wait-list hold to the rent pool
gshep Jan 23, 2024
67dc8b4
Merge remote-tracking branch 'origin/master'
gshep Jan 23, 2024
f8bd9c6
adjust staking-rewards test
gshep Jan 23, 2024
87c9b63
send mailbox rents to the pool
gshep Jan 25, 2024
cc71520
update test case for reservations rent
gshep Jan 25, 2024
3b65197
update delayed_send_user_message_payment test case to take rent charges
gshep Jan 25, 2024
0fe9760
Merge remote-tracking branch 'origin/master'
gshep Jan 25, 2024
7e53d7a
pre-commit
gshep Jan 25, 2024
610b0dc
adjust gcli claim test
gshep Jan 26, 2024
3e62d59
Merge remote-tracking branch 'origin/master'
gshep Jan 29, 2024
28dc51d
Merge remote-tracking branch 'origin/master'
gshep Feb 2, 2024
b730576
Merge remote-tracking branch 'origin/master'
gshep Feb 5, 2024
a691968
Merge remote-tracking branch 'origin/master'
gshep Feb 6, 2024
2b37e5b
std features for sp-io
gshep Feb 8, 2024
6df31cc
Merge remote-tracking branch 'origin/master'
gshep Feb 12, 2024
2c14220
fix review remark: change type of MILLISECS_PER_BLOCK back to u64
gshep Feb 12, 2024
f23f1a0
use saturating arithmetic for rewards calculation
gshep Feb 12, 2024
23074e5
fix review remarks
gshep Feb 12, 2024
6546a77
hide spend_gas method
gshep Feb 12, 2024
757afc7
fix review remarks
gshep Feb 12, 2024
9d03e34
make fmt & clippy
gshep Feb 12, 2024
1831e43
Merge remote-tracking branch 'origin/master'
gshep Feb 12, 2024
2affe97
Merge remote-tracking branch 'origin/master'
gshep Feb 13, 2024
ee0c528
Merge remote-tracking branch 'origin/master'
gshep Feb 19, 2024
5489a33
fix review comments
gshep Feb 19, 2024
ac9bf55
migration with check of rent pool account
gshep Feb 19, 2024
7a74c09
Merge remote-tracking branch 'origin/master'
gshep Feb 26, 2024
a035953
move migration check logic to pre-upgrade method
gshep Feb 27, 2024
8659796
Merge remote-tracking branch 'origin/master'
gshep Feb 27, 2024
8a5126b
Merge remote-tracking branch 'origin/master'
gshep Feb 28, 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
35 changes: 30 additions & 5 deletions common/src/pallet_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ macro_rules! impl_pallet_timestamp {

#[macro_export]
macro_rules! impl_pallet_authorship {
($runtime:ty, EventHandler = $event_handler:ty) => {
($( $tokens:tt )*) => {
#[allow(dead_code)]
pub struct FixedBlockAuthor;

impl FindAuthor<AccountId> for FixedBlockAuthor {
Expand All @@ -139,13 +140,37 @@ macro_rules! impl_pallet_authorship {
}
}

#[allow(dead_code)]
type AuthorshipFindAuthor = FixedBlockAuthor;
#[allow(dead_code)]
type AuthorshipEventHandler = ();

mod pallet_tests_authorship_config_impl {
use super::*;

$crate::impl_pallet_authorship_inner!($( $tokens )*);
}
};
}

#[macro_export]
macro_rules! impl_pallet_authorship_inner {
($runtime:ty$(,)?) => {
impl pallet_authorship::Config for $runtime {
type FindAuthor = FixedBlockAuthor;
type EventHandler = $event_handler;
type FindAuthor = AuthorshipFindAuthor;
type EventHandler = AuthorshipEventHandler;
}
};

($runtime:ty) => {
$crate::impl_pallet_authorship!($runtime, EventHandler = ());
($runtime:ty, FindAuthor = $find_author:ty $(, $( $rest:tt )*)?) => {
type AuthorshipFindAuthor = $find_author;

$crate::impl_pallet_authorship_inner!($runtime, $($( $rest )*)?);
};

($runtime:ty, EventHandler = $event_handler:ty $(, $( $rest:tt )*)?) => {
type AuthorshipEventHandler = $event_handler;

$crate::impl_pallet_authorship_inner!($runtime, $($( $rest )*)?);
};
}
18 changes: 15 additions & 3 deletions gcli/tests/cmd/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,17 @@

//! Integration tests for command `send`

use crate::common::{self, node::NodeExec, Args, Result, ALICE_SS58_ADDRESS as ADDRESS};
use crate::common::{
self, node::NodeExec, Args, Result, ALICE_SS58_ADDRESS as ADDRESS, RENT_POOL_SS58_ADDRESS,
};
use gsdk::Api;

const REWARD_PER_BLOCK: u128 = 75_000; // 3_000 gas * 25 value per gas

#[tokio::test]
async fn test_command_claim_works() -> Result<()> {
// hack to check initial alice balance
let (initial_balance, initial_stash) = {
let (initial_balance, initial_stash, rent_pool_initial) = {
let node = common::dev()?;

// Get balance of the testing address
Expand All @@ -40,6 +42,11 @@ async fn test_command_claim_works() -> Result<()> {
.get_balance(&signer.address())
.await
.unwrap_or(0),
signer
.api()
.get_balance(RENT_POOL_SS58_ADDRESS)
.await
.unwrap_or(0),
)
};

Expand All @@ -65,8 +72,13 @@ async fn test_command_claim_works() -> Result<()> {

let burned_after = signer.api().get_balance(&signer.address()).await? - initial_stash;
let after = signer.api().get_balance(ADDRESS).await?;
let rent_pool = signer.api().get_balance(RENT_POOL_SS58_ADDRESS).await?;

assert_eq!(initial_balance - before - burned_before, REWARD_PER_BLOCK);
assert_eq!(initial_balance - burned_after, after);
assert_eq!(
initial_balance - burned_after - (rent_pool - rent_pool_initial),
after
);

Ok(())
}
4 changes: 2 additions & 2 deletions gcli/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub mod node;
mod result;

pub const ALICE_SS58_ADDRESS: &str = "kGkLEU3e3XXkJp2WK4eNpVmSab5xUNL9QtmLPh8QfCL2EgotW";
pub const RENT_POOL_SS58_ADDRESS: &str = "kGkkENXuYL4Xw6H1ymWm6VwHLi66s56Ywt45pf9hEx1hmx5MV";

impl NodeExec for Node {
fn ws(&self) -> String {
Expand Down Expand Up @@ -93,8 +94,7 @@ pub fn program_id(bin: &[u8], salt: &[u8]) -> ProgramId {

/// AccountId32 of `addr`
pub fn alice_account_id() -> AccountId32 {
AccountId32::from_ss58check("kGkLEU3e3XXkJp2WK4eNpVmSab5xUNL9QtmLPh8QfCL2EgotW")
.expect("Invalid address")
AccountId32::from_ss58check(ALICE_SS58_ADDRESS).expect("Invalid address")
}

/// Create program messager
Expand Down
22 changes: 13 additions & 9 deletions pallets/gear-bank/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,14 +241,6 @@ pub mod pallet {
.map_err(|_| Error::<T>::InsufficientBankBalance)
}

/// Transfers value from bank address to current block author.
fn reward_block_author(value: BalanceOf<T>) -> Result<(), Error<T>> {
let block_author = Authorship::<T>::author()
.unwrap_or_else(|| unreachable!("Failed to find block author!"));

Self::withdraw(&block_author, value)
}

pub fn deposit_gas(
account_id: &AccountIdOf<T>,
amount: u64,
Expand Down Expand Up @@ -328,6 +320,18 @@ pub mod pallet {
account_id: &AccountIdOf<T>,
amount: u64,
multiplier: GasMultiplier<T>,
) -> Result<(), Error<T>> {
let block_author = Authorship::<T>::author()
.unwrap_or_else(|| unreachable!("Failed to find block author!"));

Self::spend_gas_to(&block_author, account_id, amount, multiplier)
}

pub fn spend_gas_to(
to: &AccountIdOf<T>,
account_id: &AccountIdOf<T>,
amount: u64,
multiplier: GasMultiplier<T>,
) -> Result<(), Error<T>> {
if amount.is_zero() {
return Ok(());
Expand All @@ -339,7 +343,7 @@ pub mod pallet {
// `*_no_transfer` function above.
//
// This call does only currency trait final transfer.
Self::reward_block_author(value).unwrap_or_else(|e| unreachable!("qed above: {e:?}"));
Self::withdraw(to, value).unwrap_or_else(|e| unreachable!("qed above: {e:?}"));

Ok(())
}
Expand Down
8 changes: 8 additions & 0 deletions pallets/gear-bank/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,8 @@ fn spend_gas_small_amount_validator_account_deleted() {
#[test]
fn spend_gas_zero() {
new_test_ext().execute_with(|| {
let _block_author = Authorship::author();
breathx marked this conversation as resolved.
Show resolved Hide resolved

let h = frame_support::storage_root(frame_support::StateVersion::V1);

assert_ok!(GearBank::spend_gas(&ALICE, 0, mult()));
Expand All @@ -573,6 +575,8 @@ fn spend_gas_zero() {
fn spend_gas_insufficient_bank_balance() {
// Unreachable case for Gear protocol.
new_test_ext().execute_with(|| {
let _block_author = Authorship::author();

const GAS_AMOUNT: u64 = 123_456;

assert_ok!(GearBank::deposit_gas(&ALICE, GAS_AMOUNT, false));
Expand All @@ -595,6 +599,8 @@ fn spend_gas_insufficient_bank_balance() {
#[test]
fn spend_gas_insufficient_gas_balance() {
new_test_ext().execute_with(|| {
let _block_author = Authorship::author();

const GAS_AMOUNT: u64 = 123_456;

assert_ok!(GearBank::deposit_gas(&ALICE, GAS_AMOUNT, false));
Expand All @@ -616,6 +622,8 @@ fn spend_gas_insufficient_gas_balance() {
#[test]
fn spend_gas_insufficient_inexistent_gas_balance() {
new_test_ext().execute_with(|| {
let _block_author = Authorship::author();

assert_noop!(
GearBank::spend_gas(&ALICE, 1, mult()),
Error::<Test>::InsufficientGasBalance
Expand Down
26 changes: 18 additions & 8 deletions pallets/gear/src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
//! Internal details of Gear Pallet implementation.

use crate::{
Config, CostsPerBlockOf, CurrencyOf, DispatchStashOf, Event, ExtManager, GasBalanceOf,
GasHandlerOf, GasNodeIdOf, GearBank, MailboxOf, Pallet, QueueOf, SchedulingCostOf, TaskPoolOf,
WaitlistOf,
AccountIdOf, Config, CostsPerBlockOf, CurrencyOf, DispatchStashOf, Event, ExtManager,
GasBalanceOf, GasHandlerOf, GasNodeIdOf, GearBank, MailboxOf, Pallet, QueueOf,
SchedulingCostOf, TaskPoolOf, WaitlistOf,
};
use alloc::collections::BTreeSet;
use common::{
Expand Down Expand Up @@ -209,7 +209,11 @@ where
///
/// Represents logic of burning gas by transferring gas from
/// current `GasTree` owner to actual block producer.
pub(crate) fn spend_gas(id: impl Into<GasNodeIdOf<T>>, amount: GasBalanceOf<T>) {
pub(crate) fn spend_gas(
breathx marked this conversation as resolved.
Show resolved Hide resolved
to: Option<AccountIdOf<T>>,
id: impl Into<GasNodeIdOf<T>>,
amount: GasBalanceOf<T>,
) {
let id = id.into();

// If amount is zero, nothing to do.
Expand All @@ -225,9 +229,15 @@ where
let (external, multiplier, _) = GasHandlerOf::<T>::get_origin_node(id)
.unwrap_or_else(|e| unreachable!("GasTree corrupted! {:?}", e));

// Transferring reserved funds from external user to block author.
GearBank::<T>::spend_gas(&external, amount, multiplier)
.unwrap_or_else(|e| unreachable!("Gear bank error: {e:?}"));
// Transferring reserved funds from external user to destination.
let result = match to {
breathx marked this conversation as resolved.
Show resolved Hide resolved
Some(account_id) => {
GearBank::<T>::spend_gas_to(&account_id, &external, amount, multiplier)
}
None => GearBank::<T>::spend_gas(&external, amount, multiplier),
};

result.unwrap_or_else(|e| unreachable!("Gear bank error: {e:?}"));
}

/// Consumes message by given `MessageId` or gas reservation by `ReservationId`.
Expand Down Expand Up @@ -315,7 +325,7 @@ where
// Spending gas, if need.
if !amount.is_zero() {
// Spending gas.
Self::spend_gas(id, amount)
Self::spend_gas(<T as Config>::RentPoolId::get(), id, amount)
breathx marked this conversation as resolved.
Show resolved Hide resolved
}
}

Expand Down
3 changes: 3 additions & 0 deletions pallets/gear/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,9 @@ pub mod pallet {
/// rent is disabled.
#[pallet::constant]
type ProgramRentDisabledDelta: Get<BlockNumberFor<Self>>;

/// The account id of the rent pool if any.
type RentPoolId: Get<Option<AccountIdOf<Self>>>;
breathx marked this conversation as resolved.
Show resolved Hide resolved
}

#[pallet::pallet]
Expand Down
2 changes: 1 addition & 1 deletion pallets/gear/src/manager/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ where

GasAllowanceOf::<T>::decrease(amount);

Pallet::<T>::spend_gas(message_id, amount)
Pallet::<T>::spend_gas(None, message_id, amount)
}

fn exit_dispatch(&mut self, id_exited: ProgramId, value_destination: ProgramId) {
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 @@ -50,6 +50,7 @@ pub(crate) const USER_2: AccountId = 2;
pub(crate) const USER_3: AccountId = 3;
pub(crate) const LOW_BALANCE_USER: AccountId = 4;
pub(crate) const BLOCK_AUTHOR: AccountId = 255;
pub(crate) const RENT_POOL: AccountId = 256;

macro_rules! dry_run {
(
Expand Down Expand Up @@ -89,7 +90,7 @@ pallet_gear_program::impl_config!(Test);
pallet_gear_messenger::impl_config!(Test, CurrentBlockNumber = Gear);
pallet_gear_scheduler::impl_config!(Test);
pallet_gear_bank::impl_config!(Test);
pallet_gear::impl_config!(Test, Schedule = DynamicSchedule);
pallet_gear::impl_config!(Test, Schedule = DynamicSchedule, RentPoolId = ConstU64<RENT_POOL>);
pallet_gear_gas::impl_config!(Test);
common::impl_pallet_balances!(Test);
common::impl_pallet_authorship!(Test);
Expand Down Expand Up @@ -191,6 +192,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
(USER_3, 500_000_000_000_000_u128),
(LOW_BALANCE_USER, 1_000_000_u128),
(BLOCK_AUTHOR, 500_000_u128),
(RENT_POOL, ExistentialDeposit::get()),
(BankAddress::get(), ExistentialDeposit::get()),
],
}
Expand Down
9 changes: 9 additions & 0 deletions pallets/gear/src/pallet_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ macro_rules! impl_config {
type GearConfigProgramRentEnabled = ConstBool<true>;
#[allow(dead_code)]
type GearConfigSchedule = ();
#[allow(dead_code)]
type GearRentPoolId = sp_runtime::traits::GetDefault;
breathx marked this conversation as resolved.
Show resolved Hide resolved

mod pallet_tests_gear_config_impl {
use super::*;
Expand Down Expand Up @@ -62,6 +64,7 @@ macro_rules! impl_config_inner {
type ProgramResumeSessionDuration = ResumeSessionDuration;
type ProgramRentEnabled = GearConfigProgramRentEnabled;
type ProgramRentDisabledDelta = RentFreePeriod;
type RentPoolId = GearRentPoolId;
}
};

Expand All @@ -82,4 +85,10 @@ macro_rules! impl_config_inner {

$crate::impl_config_inner!($runtime, $($( $rest )*)?);
};

($runtime:ty, RentPoolId = $rent_pool_id:ty $(, $( $rest:tt )*)?) => {
type GearRentPoolId = $rent_pool_id;

$crate::impl_config_inner!($runtime, $($( $rest )*)?);
};
}
Loading
Loading