Skip to content

Commit

Permalink
Add fee payer (#31)
Browse files Browse the repository at this point in the history
* add fee payer

* add metadata change

* add commission change

* remove printlns

* refactor balance changes
  • Loading branch information
Fraccaman authored May 21, 2024
1 parent 215c5b9 commit 89ecdc5
Show file tree
Hide file tree
Showing 9 changed files with 243 additions and 74 deletions.
21 changes: 11 additions & 10 deletions chain/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ use chain::services::{
use clap::Parser;
use clap_verbosity_flag::LevelFilter;
use deadpool_diesel::postgres::Object;
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use orm::migrations::run_migrations;
use orm::schema::pos_rewards;
use shared::block::Block;
use shared::block_result::BlockResult;
use shared::checksums::Checksums;
Expand Down Expand Up @@ -174,6 +172,8 @@ async fn crawling_fn(
.into_rpc_error()?;
tracing::info!("Updating unbonds for {} addresses", unbonds.len());

let metadata_change = block.validator_metadata();

let reward_claimers = block.pos_rewards();

let crawler_state = CrawlerState::new(block_height, epoch);
Expand Down Expand Up @@ -201,12 +201,15 @@ async fn crawling_fn(
crawler_state,
)?;

diesel::delete(pos_rewards::table.filter(
pos_rewards::dsl::owner.eq_any(
reward_claimers.into_iter().map(|id| id.to_string()),
),
))
.execute(transaction_conn)?;
repository::pos::delete_claimed_rewards(
transaction_conn,
reward_claimers,
)?;

repository::pos::update_validator_metadata(
transaction_conn,
metadata_change,
)?;

anyhow::Ok(())
})
Expand All @@ -233,8 +236,6 @@ async fn initial_query(
let pos_crawler_epoch =
get_pos_crawler_state(conn).await.into_db_error();

println!("{:?}, {:?}", epoch, pos_crawler_epoch);

match pos_crawler_epoch {
Ok(pos_crawler_epoch) if pos_crawler_epoch.epoch == epoch => {
break;
Expand Down
46 changes: 44 additions & 2 deletions chain/src/repository/pos.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
use std::collections::HashSet;

use anyhow::Context;
use diesel::upsert::excluded;
use diesel::{
ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl, SelectableHelper,
};
use orm::bond::BondInsertDb;
use orm::schema::{bonds, unbonds, validators};
use orm::schema::{bonds, pos_rewards, unbonds, validators};
use orm::unbond::UnbondInsertDb;
use orm::validators::ValidatorDb;
use orm::validators::{ValidatorDb, ValidatorUpdateMetadataDb};
use shared::bond::Bonds;
use shared::id::Id;
use shared::unbond::Unbonds;
use shared::validator::ValidatorMetadataChange;

pub fn insert_bonds(
transaction_conn: &mut PgConnection,
Expand Down Expand Up @@ -82,3 +86,41 @@ pub fn insert_unbonds(
.context("Failed to update unbonds in db")?;
anyhow::Ok(())
}

pub fn delete_claimed_rewards(
transaction_conn: &mut PgConnection,
reward_claimers: HashSet<Id>,
) -> anyhow::Result<()> {
diesel::delete(
pos_rewards::table.filter(
pos_rewards::dsl::owner
.eq_any(reward_claimers.into_iter().map(|id| id.to_string())),
),
)
.execute(transaction_conn)
.context("Failed to update reawrds in db")?;

anyhow::Ok(())
}

pub fn update_validator_metadata(
transaction_conn: &mut PgConnection,
metadata_change: Vec<ValidatorMetadataChange>,
) -> anyhow::Result<()> {
for metadata in metadata_change {
let metadata_change_db = ValidatorUpdateMetadataDb {
commission: metadata.commission,
email: metadata.email,
website: metadata.website,
description: metadata.description,
discord_handle: metadata.discord_handler,
avatar: metadata.avatar,
};
diesel::update(validators::table)
.set(metadata_change_db)
.filter(validators::namada_address.eq(metadata.address.to_string()))
.execute(transaction_conn)
.context("Failed to update unbonds in db")?;
}
anyhow::Ok(())
}
14 changes: 13 additions & 1 deletion orm/src/validators.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::str::FromStr;

use diesel::{Insertable, Queryable, Selectable};
use diesel::{AsChangeset, Insertable, Queryable, Selectable};
use serde::Serialize;
use shared::validator::Validator;

Expand Down Expand Up @@ -37,6 +37,18 @@ pub struct ValidatorInsertDb {
pub avatar: Option<String>,
}

#[derive(Serialize, AsChangeset, Clone)]
#[diesel(table_name = validators)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct ValidatorUpdateMetadataDb {
pub commission: Option<String>,
pub email: Option<String>,
pub website: Option<String>,
pub description: Option<String>,
pub discord_handle: Option<String>,
pub avatar: Option<String>,
}

impl ValidatorInsertDb {
pub fn from_validator(validator: Validator) -> Self {
Self {
Expand Down
164 changes: 112 additions & 52 deletions shared/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::proposal::{GovernanceProposal, GovernanceProposalKind};
use crate::transaction::{Transaction, TransactionKind};
use crate::unbond::UnbondAddresses;
use crate::utils::BalanceChange;
use crate::validator::ValidatorMetadataChange;
use crate::vote::GovernanceVote;

pub type Epoch = u32;
Expand Down Expand Up @@ -277,69 +278,78 @@ impl Block {
) -> HashSet<BalanceChange> {
self.transactions
.iter()
.filter_map(|tx| match &tx.kind {
TransactionKind::TransparentTransfer(data) => {
let transfer_data =
namada_core::token::Transfer::try_from_slice(data)
.unwrap();
let transfer_source = Id::from(transfer_data.source);
let transfer_target = Id::from(transfer_data.target);
let transfer_token = Id::from(transfer_data.token);
Some(vec![
BalanceChange::new(
transfer_source,
transfer_token.clone(),
),
BalanceChange::new(transfer_target, transfer_token),
])
}
TransactionKind::Bond(data) => {
let bond_data =
namada_tx::data::pos::Bond::try_from_slice(data)
.unwrap();
let address =
bond_data.source.unwrap_or(bond_data.validator);
.flat_map(|tx| {
let mut balance_changes = match &tx.kind {
TransactionKind::TransparentTransfer(data) => {
let transfer_data =
namada_core::token::Transfer::try_from_slice(data)
.unwrap();
let transfer_source = Id::from(transfer_data.source);
let transfer_target = Id::from(transfer_data.target);
let transfer_token = Id::from(transfer_data.token);
vec![
BalanceChange::new(
transfer_source,
transfer_token.clone(),
),
BalanceChange::new(transfer_target, transfer_token),
]
}
TransactionKind::Bond(data) => {
let bond_data =
namada_tx::data::pos::Bond::try_from_slice(data)
.unwrap();
let address =
bond_data.source.unwrap_or(bond_data.validator);

let source = Id::from(address);
let source = Id::from(address);

Some(vec![BalanceChange::new(source, native_token.clone())])
}
TransactionKind::Withdraw(data) => {
let withdraw_data =
namada_tx::data::pos::Withdraw::try_from_slice(data)
vec![BalanceChange::new(source, native_token.clone())]
}
TransactionKind::Withdraw(data) => {
let withdraw_data =
namada_tx::data::pos::Withdraw::try_from_slice(
data,
)
.unwrap();
let address =
withdraw_data.source.unwrap_or(withdraw_data.validator);
let source = Id::from(address);
let address = withdraw_data
.source
.unwrap_or(withdraw_data.validator);
let source = Id::from(address);

Some(vec![BalanceChange::new(source, native_token.clone())])
}
TransactionKind::ClaimRewards(data) => {
let claim_rewards_data =
namada_tx::data::pos::ClaimRewards::try_from_slice(
data,
)
.unwrap();
let address = claim_rewards_data
.source
.unwrap_or(claim_rewards_data.validator);
let source = Id::from(address);
vec![BalanceChange::new(source, native_token.clone())]
}
TransactionKind::ClaimRewards(data) => {
let claim_rewards_data =
namada_tx::data::pos::ClaimRewards::try_from_slice(
data,
)
.unwrap();
let address = claim_rewards_data
.source
.unwrap_or(claim_rewards_data.validator);
let source = Id::from(address);

Some(vec![BalanceChange::new(source, native_token.clone())])
}
TransactionKind::InitProposal(data) => {
let init_proposal_data =
vec![BalanceChange::new(source, native_token.clone())]
}
TransactionKind::InitProposal(data) => {
let init_proposal_data =
namada_governance::InitProposalData::try_from_slice(
data,
)
.unwrap();
let author = Id::from(init_proposal_data.author);
let author = Id::from(init_proposal_data.author);

Some(vec![BalanceChange::new(author, native_token.clone())])
}
_ => None,
vec![BalanceChange::new(author, native_token.clone())]
}
_ => vec![],
};
balance_changes.push(BalanceChange::new(
tx.fee.gas_payer.clone(),
tx.fee.gas_token.clone(),
));
balance_changes
})
.flatten()
.collect()
}

Expand Down Expand Up @@ -424,4 +434,54 @@ impl Block {
})
.collect()
}

pub fn validator_metadata(&self) -> Vec<ValidatorMetadataChange> {
self.transactions
.iter()
.filter_map(|tx| match &tx.kind {
TransactionKind::MetadataChange(data) => {
let metadata_change_data =
namada_tx::data::pos::MetaDataChange::try_from_slice(
data,
)
.unwrap();
let source_address = metadata_change_data.validator;

Some(ValidatorMetadataChange {
address: Id::from(source_address),
commission: metadata_change_data
.commission_rate
.map(|c| c.to_string()),
email: metadata_change_data.email,
description: metadata_change_data.description,
website: metadata_change_data.website,
discord_handler: metadata_change_data.discord_handle,
avatar: metadata_change_data.avatar,
})
}
TransactionKind::CommissionChange(data) => {
let commission_change =
namada_tx::data::pos::CommissionChange::try_from_slice(
data,
)
.unwrap();

let source_address = commission_change.validator;

Some(ValidatorMetadataChange {
address: Id::from(source_address),
commission: Some(
commission_change.new_rate.to_string(),
),
email: None,
description: None,
website: None,
discord_handler: None,
avatar: None,
})
}
_ => None,
})
.collect()
}
}
5 changes: 4 additions & 1 deletion shared/src/checksums.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use bimap::BiMap;
use namada_sdk::tx::{
TX_BOND_WASM, TX_CLAIM_REWARDS_WASM, TX_INIT_PROPOSAL, TX_REDELEGATE_WASM,
TX_BOND_WASM, TX_CHANGE_COMMISSION_WASM, TX_CHANGE_METADATA_WASM,
TX_CLAIM_REWARDS_WASM, TX_INIT_PROPOSAL, TX_REDELEGATE_WASM,
TX_TRANSFER_WASM, TX_UNBOND_WASM, TX_VOTE_PROPOSAL, TX_WITHDRAW_WASM,
};
use serde::Deserialize;
Expand Down Expand Up @@ -32,6 +33,8 @@ impl Checksums {
TX_CLAIM_REWARDS_WASM.to_string(),
TX_VOTE_PROPOSAL.to_string(),
TX_INIT_PROPOSAL.to_string(),
TX_CHANGE_METADATA_WASM.to_string(),
TX_CHANGE_COMMISSION_WASM.to_string(),
]
}
}
7 changes: 7 additions & 0 deletions shared/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::str::FromStr;

use namada_core::address::Address as NamadaAddress;
use namada_core::hash::Hash as NamadaHash;
use namada_sdk::key::common;
use serde::{Deserialize, Serialize};
use tendermint::account::Id as TendermintAccountId;
use tendermint::block::Id as TendermintBlockId;
Expand Down Expand Up @@ -73,3 +74,9 @@ impl From<Id> for NamadaAddress {
}
}
}

impl From<common::PublicKey> for Id {
fn from(value: common::PublicKey) -> Self {
Id::Account(value.to_string())
}
}
Loading

0 comments on commit 89ecdc5

Please sign in to comment.