Skip to content

Commit

Permalink
Merge pull request #219 from anoma/ibc-events
Browse files Browse the repository at this point in the history
Ibc events
  • Loading branch information
Fraccaman authored Dec 17, 2024
2 parents e6ec420 + 1b91539 commit d1eb8df
Show file tree
Hide file tree
Showing 31 changed files with 646 additions and 32 deletions.
10 changes: 5 additions & 5 deletions chain/src/repository/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ mod tests {

insert_tokens(conn, vec![token.clone()])?;

seed_blocks_from_balances(conn, &vec![balance.clone()])?;
seed_blocks_from_balances(conn, &[balance.clone()])?;

insert_balances(conn, vec![balance.clone()])?;

Expand Down Expand Up @@ -180,7 +180,7 @@ mod tests {
..(balance.clone())
};

seed_blocks_from_balances(conn, &vec![new_balance.clone()])?;
seed_blocks_from_balances(conn, &[new_balance.clone()])?;
insert_balances(conn, vec![new_balance])?;

let queried_balance =
Expand Down Expand Up @@ -418,7 +418,7 @@ mod tests {

insert_tokens(conn, vec![token.clone()])?;

seed_blocks_from_balances(conn, &vec![balance.clone()])?;
seed_blocks_from_balances(conn, &[balance.clone()])?;
insert_balances(conn, vec![balance.clone()])?;

let queried_balance = query_balance_by_address(conn, owner, token)?;
Expand Down Expand Up @@ -515,10 +515,10 @@ mod tests {

fn seed_blocks_from_balances(
conn: &mut PgConnection,
balances: &Vec<Balance>,
balances: &[Balance],
) -> anyhow::Result<()> {
for height in balances
.into_iter()
.iter()
.map(|balance| balance.height as i32)
.collect::<HashSet<_>>()
{
Expand Down
1 change: 1 addition & 0 deletions orm/migrations/2024-07-04-103941_crawler_state/down.sql
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
-- This file should undo anything in `up.sql`

DROP TABLE crawler_state;

DROP TYPE CRAWLER_NAME;
9 changes: 9 additions & 0 deletions orm/migrations/2024-12-01-170248_ibc_ack/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- Your SQL goes here
CREATE TYPE IBC_STATUS AS ENUM ('fail', 'success', 'timeout', 'unknown');

CREATE TABLE ibc_ack (
id VARCHAR PRIMARY KEY,
tx_hash VARCHAR NOT NULL,
timeout BIGINT NOT NULL,
status IBC_STATUS NOT NULL
);
3 changes: 3 additions & 0 deletions orm/migrations/2024-12-10-104502_transaction_types/down.sql
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
-- This file should undo anything in `up.sql`
DROP TABLE ibc_ack;

DROP TYPE IBC_STATUS;
56 changes: 56 additions & 0 deletions orm/src/ibc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use diesel::prelude::Queryable;
use diesel::{AsChangeset, Insertable, Selectable};
use serde::{Deserialize, Serialize};
use shared::transaction::{IbcAckStatus, IbcSequence};

use crate::schema::ibc_ack;

#[derive(Debug, Clone, Serialize, Deserialize, diesel_derive_enum::DbEnum)]
#[ExistingTypePath = "crate::schema::sql_types::IbcStatus"]
pub enum IbcAckStatusDb {
Unknown,
Timeout,
Fail,
Success,
}

impl From<IbcAckStatus> for IbcAckStatusDb {
fn from(value: IbcAckStatus) -> Self {
match value {
IbcAckStatus::Success => Self::Success,
IbcAckStatus::Fail => Self::Fail,
IbcAckStatus::Timeout => Self::Timeout,
IbcAckStatus::Unknown => Self::Unknown,
}
}
}

#[derive(Serialize, Queryable, Insertable, Selectable, Clone, Debug)]
#[diesel(table_name = ibc_ack)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct IbcAckDb {
pub id: String,
pub tx_hash: String,
pub timeout: i64,
pub status: IbcAckStatusDb,
}

pub type IbcAckInsertDb = IbcAckDb;

impl From<IbcSequence> for IbcAckInsertDb {
fn from(value: IbcSequence) -> Self {
Self {
id: value.id(),
tx_hash: value.tx_id.to_string(),
timeout: value.timeout as i64,
status: IbcAckStatusDb::Unknown,
}
}
}

#[derive(Serialize, AsChangeset, Clone)]
#[diesel(table_name = ibc_ack)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct IbcSequencekStatusUpdateDb {
pub status: IbcAckStatusDb,
}
1 change: 1 addition & 0 deletions orm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub mod governance_proposal;
pub mod governance_votes;
pub mod group_by_macros;
pub mod helpers;
pub mod ibc;
pub mod migrations;
pub mod parameters;
pub mod pos_rewards;
Expand Down
38 changes: 38 additions & 0 deletions orm/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ pub mod sql_types {
#[diesel(postgres_type(name = "governance_tally_type"))]
pub struct GovernanceTallyType;

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

#[derive(
diesel::query_builder::QueryId,
std::fmt::Debug,
Expand Down Expand Up @@ -209,6 +217,18 @@ diesel::table! {
}
}

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

ibc_ack (id) {
id -> Varchar,
tx_hash -> Varchar,
timeout -> Int8,
status -> IbcStatus,
}
}

diesel::table! {
ibc_token (address) {
#[max_length = 45]
Expand Down Expand Up @@ -243,6 +263,21 @@ diesel::table! {
}
}

diesel::table! {
use diesel::sql_types::*;
use super::sql_types::PaymentRecurrence;
use super::sql_types::PaymentKind;

public_good_funding (id) {
id -> Int4,
proposal_id -> Int4,
payment_recurrence -> PaymentRecurrence,
payment_kind -> PaymentKind,
receipient -> Varchar,
amount -> Numeric,
}
}

diesel::table! {
revealed_pk (id) {
id -> Int4,
Expand Down Expand Up @@ -315,6 +350,7 @@ diesel::joinable!(governance_votes -> governance_proposals (proposal_id));
diesel::joinable!(ibc_token -> token (address));
diesel::joinable!(inner_transactions -> wrapper_transactions (wrapper_id));
diesel::joinable!(pos_rewards -> validators (validator_id));
diesel::joinable!(public_good_funding -> governance_proposals (proposal_id));
diesel::joinable!(unbonds -> validators (validator_id));
diesel::joinable!(wrapper_transactions -> blocks (block_height));

Expand All @@ -328,9 +364,11 @@ diesel::allow_tables_to_appear_in_same_query!(
gas_price,
governance_proposals,
governance_votes,
ibc_ack,
ibc_token,
inner_transactions,
pos_rewards,
public_good_funding,
revealed_pk,
token,
unbonds,
Expand Down
1 change: 0 additions & 1 deletion rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ format_macro_matchers = true
format_strings = true
group_imports = "StdExternalCrate"
hard_tabs = false
show_parse_errors = true
ignore = []
imports_granularity = "Module"
imports_indent = "Block"
Expand Down
4 changes: 2 additions & 2 deletions shared/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ pub struct Block {
pub hash: Id,
pub header: BlockHeader,
pub transactions: Vec<(WrapperTransaction, Vec<InnerTransaction>)>,
pub epoch: Epoch,
pub epoch: Epoch
}

impl Block {
Expand Down Expand Up @@ -154,7 +154,7 @@ impl Block {
app_hash: Id::from(&block_response.block.header.app_hash),
},
transactions,
epoch,
epoch
}
}

Expand Down
81 changes: 72 additions & 9 deletions shared/src/block_result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ use crate::transaction::TransactionExitStatus;
#[derive(Debug, Clone)]
pub enum EventKind {
Applied,
SendPacket,
Unknown,
}

impl From<&String> for EventKind {
fn from(value: &String) -> Self {
match value.as_str() {
"tx/applied" => Self::Applied,
"send_packet" => Self::SendPacket,
_ => Self::Unknown,
}
}
Expand All @@ -32,7 +34,7 @@ pub struct BlockResult {
#[derive(Debug, Clone)]
pub struct Event {
pub kind: EventKind,
pub attributes: Option<TxAttributes>,
pub attributes: Option<TxAttributesType>,
}

#[derive(Debug, Clone, Default, Copy)]
Expand Down Expand Up @@ -107,7 +109,7 @@ impl BatchResults {
}

#[derive(Debug, Clone, Default)]
pub struct TxAttributes {
pub struct TxApplied {
pub code: TxEventStatusCode,
pub gas: u64,
pub hash: Id,
Expand All @@ -116,14 +118,59 @@ pub struct TxAttributes {
pub info: String,
}

impl TxAttributes {
#[derive(Debug, Clone, Default)]
pub struct SendPacket {
pub source_port: String,
pub dest_port: String,
pub source_channel: String,
pub dest_channel: String,
pub timeout_timestamp: u64,
pub sequence: String,
}

#[derive(Debug, Clone)]
pub enum TxAttributesType {
TxApplied(TxApplied),
SendPacket(SendPacket),
}

impl TxAttributesType {
pub fn deserialize(
event_kind: &EventKind,
attributes: &BTreeMap<String, String>,
) -> Option<Self> {
match event_kind {
EventKind::Unknown => None,
EventKind::Applied => Some(Self {
EventKind::SendPacket => {
let source_port =
attributes.get("packet_src_port").unwrap().to_owned();
let dest_port =
attributes.get("packet_dst_port").unwrap().to_owned();
let source_channel =
attributes.get("packet_src_channel").unwrap().to_owned();
let dest_channel =
attributes.get("packet_dst_channel").unwrap().to_owned();
let sequence =
attributes.get("packet_sequence").unwrap().to_owned();
let timeout_timestamp = attributes
.get("packet_timeout_timestamp")
.unwrap_or(&"0".to_string())
.parse::<u64>()
.unwrap_or_default()
.to_owned();

tracing::error!("{}", timeout_timestamp);

Some(Self::SendPacket(SendPacket {
source_port,
dest_port,
source_channel,
dest_channel,
timeout_timestamp,
sequence,
}))
}
EventKind::Applied => Some(Self::TxApplied(TxApplied {
code: attributes
.get("code")
.map(|code| TxEventStatusCode::from(code.as_str()))
Expand Down Expand Up @@ -153,7 +200,7 @@ impl TxAttributes {
})
.unwrap(),
info: attributes.get("info").unwrap().to_owned(),
}),
})),
}
}
}
Expand All @@ -177,7 +224,7 @@ impl From<TendermintBlockResultResponse> for BlockResult {
},
);
let attributes =
TxAttributes::deserialize(&kind, &raw_attributes);
TxAttributesType::deserialize(&kind, &raw_attributes);
Event { kind, attributes }
})
.collect::<Vec<Event>>();
Expand All @@ -198,7 +245,7 @@ impl From<TendermintBlockResultResponse> for BlockResult {
},
);
let attributes =
TxAttributes::deserialize(&kind, &raw_attributes);
TxAttributesType::deserialize(&kind, &raw_attributes);
Event { kind, attributes }
})
.collect::<Vec<Event>>();
Expand All @@ -221,7 +268,15 @@ impl BlockResult {
let exit_status = self
.end_events
.iter()
.filter_map(|event| event.attributes.clone())
.filter_map(|event| {
if let Some(TxAttributesType::TxApplied(data)) =
&event.attributes
{
Some(data.clone())
} else {
None
}
})
.find(|attributes| attributes.hash.eq(tx_hash))
.map(|attributes| attributes.clone().code)
.map(TransactionExitStatus::from);
Expand All @@ -237,7 +292,15 @@ impl BlockResult {
let exit_status = self
.end_events
.iter()
.filter_map(|event| event.attributes.clone())
.filter_map(|event| {
if let Some(TxAttributesType::TxApplied(data)) =
&event.attributes
{
Some(data.clone())
} else {
None
}
})
.find(|attributes| attributes.hash.eq(wrapper_hash))
.map(|attributes| attributes.batch.is_successful(inner_hash))
.map(|successful| match successful {
Expand Down
Loading

0 comments on commit d1eb8df

Please sign in to comment.