Skip to content

Commit

Permalink
Add paydayPoolReward logic
Browse files Browse the repository at this point in the history
  • Loading branch information
DOBEN committed Feb 7, 2025
1 parent dad30a5 commit d523f1d
Show file tree
Hide file tree
Showing 5 changed files with 169 additions and 19 deletions.

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

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

50 changes: 38 additions & 12 deletions backend-rust/src/graphql_api/baker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ pub struct Baker {
transaction_commission: Option<i64>,
baking_commission: Option<i64>,
finalization_commission: Option<i64>,
payday_transaction_commission: Option<i64>,
payday_baking_commission: Option<i64>,
payday_finalization_commission: Option<i64>,
}
impl Baker {
pub async fn query_by_id(pool: &PgPool, baker_id: i64) -> ApiResult<Option<Self>> {
Expand All @@ -94,7 +97,10 @@ impl Baker {
metadata_url,
transaction_commission,
baking_commission,
finalization_commission
finalization_commission,
payday_transaction_commission,
payday_baking_commission,
payday_finalization_commission
FROM bakers
WHERE id = $1
"#,
Expand Down Expand Up @@ -128,6 +134,21 @@ impl Baker {
.map(u32::try_from)
.transpose()?
.map(|c| AmountFraction::new_unchecked(c).into());
let payday_transaction_commission = self
.payday_transaction_commission
.map(u32::try_from)
.transpose()?
.map(|c| AmountFraction::new_unchecked(c).into());
let payday_baking_commission = self
.payday_baking_commission
.map(u32::try_from)
.transpose()?
.map(|c| AmountFraction::new_unchecked(c).into());
let payday_finalization_commission = self
.payday_finalization_commission
.map(u32::try_from)
.transpose()?
.map(|c| AmountFraction::new_unchecked(c).into());

let total_stake: i64 =
sqlx::query_scalar!("SELECT total_staked FROM blocks ORDER BY height DESC LIMIT 1")
Expand Down Expand Up @@ -161,7 +182,7 @@ impl Baker {
.ok_or_else(|| ApiError::InternalError("Division by zero".to_string()))?
.into();

let out = BakerState::ActiveBakerState(ActiveBakerState {
let out = BakerState::ActiveBakerState(Box::new(ActiveBakerState {
staked_amount: Amount::try_from(self.staked)?,
restake_earnings: self.restake_earnings,
pool: BakerPool {
Expand All @@ -171,14 +192,19 @@ impl Baker {
baking_commission,
finalization_commission,
},
payday_commission_rates: CommissionRates {
transaction_commission: payday_transaction_commission,
baking_commission: payday_baking_commission,
finalization_commission: payday_finalization_commission,
},
metadata_url: self.metadata_url.as_deref(),
total_stake_percentage,
total_stake: total_pool_stake.try_into()?,
delegated_stake: delegated_stake.try_into()?,
delegator_count: row.delegator_count.unwrap_or(0),
},
pending_change: None, // This is not used starting from P7.
});
}));
Ok(out)
}

Expand Down Expand Up @@ -313,7 +339,7 @@ struct InterimTransaction {

#[derive(Union)]
enum BakerState<'a> {
ActiveBakerState(ActiveBakerState<'a>),
ActiveBakerState(Box<ActiveBakerState<'a>>),
RemovedBakerState(RemovedBakerState),
}

Expand Down Expand Up @@ -378,26 +404,26 @@ enum BakerSort {
struct BakerPool<'a> {
/// Total stake of the baker pool as a percentage of all CCDs in existence.
/// Includes both baker stake and delegated stake.
total_stake_percentage: Decimal,
total_stake_percentage: Decimal,
/// The total amount staked in this baker pool. Includes both baker stake
/// and delegated stake.
total_stake: Amount,
total_stake: Amount,
/// The total amount staked by delegators to this baker pool.
delegated_stake: Amount,
delegated_stake: Amount,
/// The number of delegators that delegate to this baker pool.
delegator_count: i64,
delegator_count: i64,
payday_commission_rates: CommissionRates,
// lottery_power: Decimal,
// payday_commission_rates: CommissionRates,
// /// Ranking of the baker pool by total staked amount. Value may be null for
// /// brand new bakers where statistics have not been calculated yet. This
// /// should be rare and only a temporary condition.
// ranking_by_total_stake: Ranking,
// /// The maximum amount that may be delegated to the pool, accounting for
// /// leverage and stake limits.
// delegated_stake_cap: Amount,
open_status: Option<BakerPoolOpenStatus>,
commission_rates: CommissionRates,
metadata_url: Option<&'a str>,
open_status: Option<BakerPoolOpenStatus>,
commission_rates: CommissionRates,
metadata_url: Option<&'a str>,
// TODO: apy(period: ApyPeriod!): PoolApy!
// TODO: delegators("Returns the first _n_ elements from the list." first: Int "Returns the
// elements in the list that come after the specified cursor." after: String "Returns the last
Expand Down
87 changes: 82 additions & 5 deletions backend-rust/src/indexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3758,13 +3758,31 @@ enum PreparedSpecialTransactionOutcomeUpdate {
Rewards(Vec<PreparedUpdateAccountBalance>),
/// Represents a payday block with its CCD mint rewards and its block
/// height.
Payday(PreparedPayDayBlock),
Payday(Payday),
/// Validator is primed for suspension.
ValidatorPrimedForSuspension(PreparedValidatorPrimedForSuspension),
/// Validator is suspended.
ValidatorSuspended(PreparedValidatorSuspension),
}

enum Payday {
/// Distribution of various CCD rewards. Excluding CCD mint rewards.
PreparedPaydayPoolReward(PreparedPaydayPoolReward),
PreparedPayDayBlock(PreparedPayDayBlock),
}

impl Payday {
async fn save(
&self,
tx: &mut sqlx::Transaction<'static, sqlx::Postgres>,
) -> anyhow::Result<()> {
match self {
Self::PreparedPaydayPoolReward(event) => event.save(tx).await,
Self::PreparedPayDayBlock(event) => event.save(tx).await,
}
}
}

impl PreparedSpecialTransactionOutcomeUpdate {
fn prepare(
event: &SpecialTransactionOutcome,
Expand Down Expand Up @@ -3802,7 +3820,10 @@ impl PreparedSpecialTransactionOutcomeUpdate {
AccountStatementEntryType::FoundationReward,
)?;

Self::Payday(PreparedPayDayBlock::prepare(block_height, rewards)?)
Self::Payday(Payday::PreparedPayDayBlock(PreparedPayDayBlock::prepare(
block_height,
rewards,
)?))
}
SpecialTransactionOutcome::FinalizationRewards {
finalization_rewards,
Expand Down Expand Up @@ -3881,10 +3902,18 @@ impl PreparedSpecialTransactionOutcomeUpdate {
// TODO: Support these two types. (Deviates from Old CCDScan)
SpecialTransactionOutcome::BlockAccrueReward {
..
}
| SpecialTransactionOutcome::PaydayPoolReward {
..
} => Self::Rewards(Vec::new()),
SpecialTransactionOutcome::PaydayPoolReward {
pool_owner,
transaction_fees,
baker_reward,
finalization_reward,
} => Self::Payday(Payday::PreparedPaydayPoolReward(PreparedPaydayPoolReward::prepare(
pool_owner.map(|i| i.id.index as i64),
*transaction_fees,
*baker_reward,
*finalization_reward,
)?)),
SpecialTransactionOutcome::ValidatorSuspended {
baker_id,
..
Expand Down Expand Up @@ -4056,6 +4085,54 @@ impl PreparedPayDayBlock {
}
}

/// Represents a payday pool rewards distributed to bakers captured from the
/// `SpecialTransactionOutcome::PaydayPoolReward` event.
struct PreparedPaydayPoolReward {
baker_id: Option<i64>,
transaction_fees: i64,
baker_reward: i64,
finalization_reward: i64,
}

impl PreparedPaydayPoolReward {
fn prepare(
pool_owner: Option<i64>,
transaction_fees: Amount,
baker_reward: Amount,
finalization_reward: Amount,
) -> anyhow::Result<Self> {
Ok(Self {
baker_id: pool_owner,
transaction_fees: transaction_fees.micro_ccd.try_into()?,
baker_reward: baker_reward.micro_ccd.try_into()?,
finalization_reward: finalization_reward.micro_ccd.try_into()?,
})
}

async fn save(
&self,
tx: &mut sqlx::Transaction<'static, sqlx::Postgres>,
) -> anyhow::Result<()> {
if let Some(baker_id) = self.baker_id {
sqlx::query!(
"UPDATE bakers
SET
payday_transaction_commission = $2,
payday_baking_commission = $3,
payday_finalization_commission = $4
WHERE id=$1",
baker_id,
self.transaction_fees,
self.baker_reward,
self.finalization_reward
)
.execute(tx.as_mut())
.await?;
};
Ok(())
}
}

impl PreparedValidatorSuspension {
fn prepare(baker_id: &BakerId, block_height: AbsoluteBlockHeight) -> anyhow::Result<Self> {
Ok(Self {
Expand Down
12 changes: 12 additions & 0 deletions backend-rust/src/migrations/m0001-initialize.sql
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,18 @@ CREATE TABLE bakers(
-- Stored as a fraction of an amount with a precision of `1/100_000`.
finalization_commission
BIGINT,
-- Fraction of transaction rewards rewarded at payday to this baker pool.
-- Stored as a fraction of an amount with a precision of `1/100_000`.
payday_transaction_commission
BIGINT,
-- Fraction of baking rewards rewarded at payday to this baker pool.
-- Stored as a fraction of an amount with a precision of `1/100_000`.
payday_baking_commission
BIGINT,
-- Fraction of finalization rewards rewarded at payday to this baker pool.
-- Stored as a fraction of an amount with a precision of `1/100_000`.
payday_finalization_commission
BIGINT,
-- Transaction used for self-suspending.
-- This is not null only when a baker is suspended due to sending the transaction for
-- self-suspending.
Expand Down

0 comments on commit d523f1d

Please sign in to comment.