Skip to content

Commit

Permalink
Merge pull request #304 from anoma/fix-default-gas
Browse files Browse the repository at this point in the history
refactor default gas
  • Loading branch information
Fraccaman authored Feb 25, 2025
2 parents ac5a48e + ca84392 commit bfedfeb
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 115 deletions.
2 changes: 2 additions & 0 deletions orm/migrations/2025-02-25-085529_drop-gas/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
SELECT 1;
2 changes: 2 additions & 0 deletions orm/migrations/2025-02-25-085529_drop-gas/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Your SQL goes here
DROP TABLE IF EXISTS gas;
11 changes: 1 addition & 10 deletions orm/src/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,7 @@ use bigdecimal::BigDecimal;
use diesel::{Insertable, Queryable, Selectable};
use shared::gas::{GasEstimation, GasPrice};

use crate::schema::{gas, gas_estimations, gas_price};
use crate::transactions::TransactionKindDb;

#[derive(Clone, Queryable, Selectable)]
#[diesel(table_name = gas)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct GasDb {
pub tx_kind: TransactionKindDb,
pub gas_limit: i32,
}
use crate::schema::{gas_estimations, gas_price};

#[derive(Clone, Queryable, Selectable, Insertable)]
#[diesel(table_name = gas_price)]
Expand Down
28 changes: 8 additions & 20 deletions orm/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,32 +38,32 @@ pub mod sql_types {
std::fmt::Debug,
diesel::sql_types::SqlType,
)]
#[diesel(postgres_type(name = "payment_kind"))]
pub struct PaymentKind;
#[diesel(postgres_type(name = "history_kind"))]
pub struct HistoryKind;

#[derive(
diesel::query_builder::QueryId,
std::fmt::Debug,
diesel::sql_types::SqlType,
)]
#[diesel(postgres_type(name = "payment_recurrence"))]
pub struct PaymentRecurrence;
#[diesel(postgres_type(name = "ibc_status"))]
pub struct IbcStatus;

#[derive(
diesel::query_builder::QueryId,
std::fmt::Debug,
diesel::sql_types::SqlType,
)]
#[diesel(postgres_type(name = "history_kind"))]
pub struct HistoryKind;
#[diesel(postgres_type(name = "payment_kind"))]
pub struct PaymentKind;

#[derive(
diesel::query_builder::QueryId,
std::fmt::Debug,
diesel::sql_types::SqlType,
)]
#[diesel(postgres_type(name = "ibc_status"))]
pub struct IbcStatus;
#[diesel(postgres_type(name = "payment_recurrence"))]
pub struct PaymentRecurrence;

#[derive(
diesel::query_builder::QueryId,
Expand Down Expand Up @@ -172,17 +172,6 @@ diesel::table! {
}
}

diesel::table! {
use diesel::sql_types::*;
use super::sql_types::TransactionKind;

gas (id) {
id -> Int4,
tx_kind -> TransactionKind,
gas_limit -> Int4,
}
}

diesel::table! {
gas_estimations (id) {
id -> Int4,
Expand Down Expand Up @@ -444,7 +433,6 @@ diesel::allow_tables_to_appear_in_same_query!(
bonds,
chain_parameters,
crawler_state,
gas,
gas_estimations,
gas_price,
governance_proposals,
Expand Down
1 change: 0 additions & 1 deletion webserver/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ impl ApplicationServer {
"/revealed-public-key/:address",
get(pk_handlers::get_revealed_pk),
)
.route("/gas", get(gas_handlers::get_gas))
.route("/gas/estimate", get(gas_handlers::get_gas_estimate))
.route(
"/gas-price/:token",
Expand Down
12 changes: 1 addition & 11 deletions webserver/src/handler/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,9 @@ use axum_macros::debug_handler;

use crate::dto::gas::GasEstimateQuery;
use crate::error::api::ApiError;
use crate::response::gas::{Gas, GasEstimate, GasPrice};
use crate::response::gas::{GasEstimate, GasPrice};
use crate::state::common::CommonState;

#[debug_handler]
pub async fn get_gas(
_headers: HeaderMap,
State(state): State<CommonState>,
) -> Result<Json<Vec<Gas>>, ApiError> {
let gas = state.gas_service.get_gas().await;

Ok(Json(gas))
}

#[debug_handler]
pub async fn get_gas_price_by_token(
_headers: HeaderMap,
Expand Down
17 changes: 2 additions & 15 deletions webserver/src/repository/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use diesel::{
ExpressionMethods, IntoSql, JoinOnDsl, QueryDsl, RunQueryDsl,
SelectableHelper,
};
use orm::gas::{GasDb, GasPriceDb};
use orm::schema::{gas, gas_estimations, gas_price, wrapper_transactions};
use orm::gas::GasPriceDb;
use orm::schema::{gas_estimations, gas_price, wrapper_transactions};

use crate::appstate::AppState;

Expand All @@ -20,8 +20,6 @@ pub struct GasRepository {
pub trait GasRepositoryTrait {
fn new(app_state: AppState) -> Self;

async fn get_gas(&self) -> Result<Vec<GasDb>, String>;

async fn find_gas_price_by_token(
&self,
token: String,
Expand Down Expand Up @@ -57,17 +55,6 @@ impl GasRepositoryTrait for GasRepository {
Self { app_state }
}

async fn get_gas(&self) -> Result<Vec<GasDb>, String> {
let conn = self.app_state.get_db_connection().await;

conn.interact(move |conn| {
gas::table.select(GasDb::as_select()).get_results(conn)
})
.await
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string())
}

async fn find_gas_price_by_token(
&self,
token: String,
Expand Down
20 changes: 1 addition & 19 deletions webserver/src/response/gas.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,6 @@
use orm::gas::{GasDb, GasPriceDb};
use orm::gas::GasPriceDb;
use serde::{Deserialize, Serialize};

use super::transaction::TransactionKind;

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Gas {
pub gas_limit: u64,
pub tx_kind: TransactionKind,
}

impl From<GasDb> for Gas {
fn from(value: GasDb) -> Self {
Self {
gas_limit: value.gas_limit as u64,
tx_kind: TransactionKind::from(value.tx_kind),
}
}
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GasPrice {
Expand Down
112 changes: 73 additions & 39 deletions webserver/src/service/gas.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,25 @@
use std::collections::HashMap;

use bigdecimal::ToPrimitive;

use crate::appstate::AppState;
use crate::error::gas::GasError;
use crate::repository::gas::{GasRepository, GasRepositoryTrait};
use crate::response::gas::{Gas, GasEstimate, GasPrice};
use crate::response::gas::{GasEstimate, GasPrice};
use crate::response::transaction::TransactionKind;

#[derive(Clone)]
pub struct GasService {
gas_repo: GasRepository,
default_gas_table: DefaultGasTable,
}

impl GasService {
pub fn new(app_state: AppState) -> Self {
Self {
gas_repo: GasRepository::new(app_state),
default_gas_table: DefaultGasTable::default(),
}
}

pub async fn get_gas(&self) -> Vec<Gas> {
self.gas_repo
.get_gas()
.await
.unwrap_or_default()
.into_iter()
.map(Gas::from)
.collect()
}

pub async fn get_gas_price_by_token(
&self,
token: String,
Expand Down Expand Up @@ -94,7 +84,7 @@ impl GasService {
.map(|(min, max, avg, count)| {
let min = min.map(|gas| gas as u64);
let max = max.map(|gas| gas as u64);
let avg = avg.map(|gas| gas.to_i64().unwrap() as u64);
let avg = avg.map(|gas| gas.to_f64().unwrap() as u64);
let count = count as u64;
(min, max, avg, count)
})?;
Expand All @@ -108,39 +98,55 @@ impl GasService {
total_estimates: count,
})
} else {
let gas = self
.gas_repo
.get_gas()
.await
.unwrap_or_default()
.into_iter()
.map(Gas::from)
.fold(HashMap::new(), |mut acc, gas| {
acc.insert(gas.tx_kind, gas.gas_limit);
acc
});

let mut estimate = 0;
estimate += bond * gas.get(&TransactionKind::Bond).unwrap();
estimate += bond
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::Bond);
estimate += claim_rewards
* gas.get(&TransactionKind::ClaimRewards).unwrap();
estimate += unbond * gas.get(&TransactionKind::Unbond).unwrap();
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::ClaimRewards);
estimate += unbond
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::Unbond);
estimate += transparent_transfer
* gas.get(&TransactionKind::TransparentTransfer).unwrap();
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::TransparentTransfer);
estimate += shielded_transfer
* gas.get(&TransactionKind::ShieldedTransfer).unwrap();
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::ShieldedTransfer);
estimate += shielding_transfer
* gas.get(&TransactionKind::ShieldingTransfer).unwrap();
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::ShieldingTransfer);
estimate += unshielding_transfer
* gas.get(&TransactionKind::UnshieldingTransfer).unwrap();
estimate += vote * gas.get(&TransactionKind::VoteProposal).unwrap();
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::UnshieldingTransfer);
estimate += vote
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::VoteProposal);
estimate += ibc_shielding_transfer
* gas.get(&TransactionKind::IbcShieldingTransfer).unwrap();
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::IbcShieldingTransfer);
estimate += ibc_unshielding_transfer
* gas.get(&TransactionKind::IbcUnshieldingTransfer).unwrap();
estimate += withdraw * gas.get(&TransactionKind::Withdraw).unwrap();
estimate +=
reveal_pk * gas.get(&TransactionKind::RevealPk).unwrap();
* self.default_gas_table.get_gas_by_tx_kind(
TransactionKind::IbcUnshieldingTransfer,
);
estimate += withdraw
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::Withdraw);
estimate += reveal_pk
* self
.default_gas_table
.get_gas_by_tx_kind(TransactionKind::RevealPk);

Ok(GasEstimate {
min: estimate,
Expand All @@ -151,3 +157,31 @@ impl GasService {
}
}
}

#[derive(Debug, Clone, Default)]
struct DefaultGasTable {}

impl DefaultGasTable {
fn get_gas_by_tx_kind(&self, tx_kind: TransactionKind) -> u64 {
match tx_kind {
TransactionKind::Bond => 50000,
TransactionKind::ClaimRewards => 50000,
TransactionKind::Unbond => 50000,
TransactionKind::TransparentTransfer => 50000,
TransactionKind::ShieldedTransfer => 50000,
TransactionKind::ShieldingTransfer => 50000,
TransactionKind::UnshieldingTransfer => 50000,
TransactionKind::VoteProposal => 50000,
TransactionKind::IbcShieldingTransfer => 50000,
TransactionKind::IbcUnshieldingTransfer => 50000,
TransactionKind::Withdraw => 50000,
TransactionKind::RevealPk => 25000,
TransactionKind::MixedTransfer => 50000,
TransactionKind::Redelegation => 100000,
TransactionKind::InitProposal => 50000,
TransactionKind::IbcMsgTransfer => 50000,
TransactionKind::IbcTransparentTransfer => 50000,
_ => 0,
}
}
}

0 comments on commit bfedfeb

Please sign in to comment.