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: tokens and ibc tokens tables #124

Merged
merged 4 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ validator = { version = "0.16.0", features = ["derive"] }
derive_builder = "0.12.0"
clap-verbosity-flag = "2.1.1"
duration-str = "0.7.1"
fake = { version = "2.9.2", features = ["derive"] }
fake = { version = "2.10.0", features = ["derive"] }
rand = "0.8.5"
bigdecimal = "0.4.5"
strum = "0.26.3"
Expand Down
14 changes: 13 additions & 1 deletion chain/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use chain::repository;
use chain::services::db::get_pos_crawler_state;
use chain::services::namada::{
query_all_balances, query_all_bonds_and_unbonds, query_all_proposals,
query_bonds, query_last_block_height,
query_bonds, query_last_block_height, query_tokens,
};
use chain::services::{
db as db_service, namada as namada_service,
Expand All @@ -28,6 +28,7 @@ use shared::crawler::crawl;
use shared::crawler_state::ChainCrawlerState;
use shared::error::{AsDbError, AsRpcError, ContextDbInteractError, MainError};
use shared::id::Id;
use shared::token::Token;
use tendermint_rpc::HttpClient;
use tokio::time::sleep;
use tracing::Level;
Expand Down Expand Up @@ -157,6 +158,8 @@ async fn crawling_fn(
.await
.into_rpc_error()?;

let ibc_tokens = block.ibc_tokens().into_iter().map(Token::Ibc).collect();

let addresses = block.addresses_with_balance_change(native_token);
let balances = namada_service::query_balance(&client, &addresses)
.await
Expand Down Expand Up @@ -226,6 +229,11 @@ async fn crawling_fn(
conn.build_transaction()
.read_write()
.run(|transaction_conn| {
repository::balance::insert_tokens(
transaction_conn,
ibc_tokens,
)?;

repository::balance::insert_balance(
transaction_conn,
balances,
Expand Down Expand Up @@ -321,6 +329,8 @@ async fn initial_query(
sleep(Duration::from_secs(initial_query_retry_time)).await;
}

let tokens = query_tokens(client).await.into_rpc_error()?;

let balances = query_all_balances(client).await.into_rpc_error()?;

tracing::info!("Querying bonds and unbonds...");
Expand Down Expand Up @@ -357,6 +367,8 @@ async fn initial_query(
conn.build_transaction()
.read_write()
.run(|transaction_conn| {
repository::balance::insert_tokens(transaction_conn, tokens)?;

repository::balance::insert_balance_in_chunks(
transaction_conn,
balances,
Expand Down
119 changes: 98 additions & 21 deletions chain/src/repository/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ use diesel::{
sql_query, ExpressionMethods, PgConnection, QueryableByName, RunQueryDsl,
};
use orm::balances::BalancesInsertDb;
use orm::schema::balances;
use orm::schema::{balances, ibc_token, token};
use orm::token::{IbcTokenInsertDb, TokenInsertDb};
use shared::balance::Balances;
use shared::token::Token;
pub const MAX_PARAM_SIZE: u16 = u16::MAX;

#[derive(QueryableByName)]
Expand Down Expand Up @@ -62,6 +64,32 @@ pub fn insert_balance_in_chunks(
anyhow::Ok(())
}

pub fn insert_tokens(
transaction_conn: &mut PgConnection,
tokens: Vec<Token>,
) -> anyhow::Result<()> {
let tokens_db = tokens.iter().map(TokenInsertDb::from).collect::<Vec<_>>();

let ibc_tokens_db = tokens
.iter()
.filter_map(IbcTokenInsertDb::from_token)
.collect::<Vec<_>>();

diesel::insert_into(token::table)
.values(tokens_db)
.on_conflict_do_nothing()
.execute(transaction_conn)
.context("Failed to update tokens in db")?;

diesel::insert_into(ibc_token::table)
.values(ibc_tokens_db)
.on_conflict_do_nothing()
.execute(transaction_conn)
.context("Failed to update ibc tokens in db")?;

anyhow::Ok(())
}

#[cfg(test)]
mod tests {

Expand Down Expand Up @@ -103,9 +131,9 @@ mod tests {
let owner = Id::Account(
"tnam1qqshvryx9pngpk7mmzpzkjkm6klelgusuvmkc0uz".to_string(),
);
let token = Id::Account(
let token = Token::Native(Id::Account(
"tnam1q87wtaqqtlwkw927gaff34hgda36huk0kgry692a".to_string(),
);
));
let amount = Amount::from(NamadaAmount::from_u64(100));

let balance = Balance {
Expand All @@ -114,6 +142,8 @@ mod tests {
amount: amount.clone(),
};

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

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

let queried_balance = query_balance_by_address(conn, owner, token)?;
Expand All @@ -135,9 +165,9 @@ mod tests {
let owner = Id::Account(
"tnam1qqshvryx9pngpk7mmzpzkjkm6klelgusuvmkc0uz".to_string(),
);
let token = Id::Account(
let token = Token::Native(Id::Account(
"tnam1q87wtaqqtlwkw927gaff34hgda36huk0kgry692a".to_string(),
);
));
let amount = Amount::from(NamadaAmount::from_u64(100));

let balance = Balance {
Expand Down Expand Up @@ -177,9 +207,9 @@ mod tests {
let owner = Id::Account(
"tnam1qqshvryx9pngpk7mmzpzkjkm6klelgusuvmkc0uz".to_string(),
);
let token = Id::Account(
let token = Token::Native(Id::Account(
"tnam1qxfj3sf6a0meahdu9t6znp05g8zx4dkjtgyn9gfu".to_string(),
);
));
let amount = Amount::from(NamadaAmount::from_u64(100));

let balance = Balance {
Expand All @@ -192,15 +222,17 @@ mod tests {
seed_balance(conn, vec![balance.clone()])?;

let new_amount = Amount::from(NamadaAmount::from_u64(200));
let new_token = Id::Account(
let new_token = Token::Native(Id::Account(
"tnam1q87wtaqqtlwkw927gaff34hgda36huk0kgry692a".to_string(),
);
));
let new_balance = Balance {
token: new_token.clone(),
amount: new_amount.clone(),
..(balance.clone())
};

seed_tokens_from_balance(conn, vec![new_balance.clone()])?;

insert_balance(conn, vec![new_balance])?;

let queried_balance =
Expand Down Expand Up @@ -232,9 +264,9 @@ mod tests {
let owner = Id::Account(
"tnam1qqshvryx9pngpk7mmzpzkjkm6klelgusuvmkc0uz".to_string(),
);
let token = Id::Account(
let token = Token::Native(Id::Account(
"tnam1qxfj3sf6a0meahdu9t6znp05g8zx4dkjtgyn9gfu".to_string(),
);
));
let amount = Amount::from(NamadaAmount::from_u64(100));

let balance = Balance {
Expand Down Expand Up @@ -289,6 +321,8 @@ mod tests {
let fake_balances =
(0..10000).map(|_| Balance::fake()).collect::<Vec<_>>();

seed_tokens_from_balance(conn, fake_balances.clone())?;

insert_balance(conn, fake_balances.clone())?;

assert_eq!(query_all_balances(conn)?.len(), fake_balances.len());
Expand All @@ -308,9 +342,9 @@ mod tests {
let owner = Id::Account(
"tnam1qqshvryx9pngpk7mmzpzkjkm6klelgusuvmkc0uz".to_string(),
);
let token = Id::Account(
let token = Token::Native(Id::Account(
"tnam1q87wtaqqtlwkw927gaff34hgda36huk0kgry692a".to_string(),
);
));
let max_amount = Amount::from(NamadaAmount::from(MAX_SIGNED_VALUE));

let balance = Balance {
Expand All @@ -319,6 +353,8 @@ mod tests {
amount: max_amount.clone(),
};

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

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

let queried_balance = query_balance_by_address(conn, owner, token)?;
Expand All @@ -339,12 +375,21 @@ mod tests {
db.run_test(|conn| {
let mps = MAX_PARAM_SIZE as u32;

let balances =
(0..mps + 1).map(|_| Balance::fake()).collect::<Vec<_>>();
let token = Token::Native(Id::Account(
"tnam1q87wtaqqtlwkw927gaff34hgda36huk0kgry692a".to_string(),
));

// We have to fake_with_token otherwise we won't be able to seed
// MAX_PARAM_SIZE + 1 tokens and test will panic
let balances = (0..mps + 1)
.map(|_| Balance::fake_with_token(token.clone()))
.collect::<Vec<_>>();

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

let res = insert_balance_in_chunks(conn, balances)?;
let res = insert_balance_in_chunks(conn, balances);

assert_eq!(res, ());
assert!(res.is_ok());

anyhow::Ok(())
})
Expand All @@ -361,20 +406,47 @@ mod tests {
let balances =
(0..1000).map(|_| Balance::fake()).collect::<Vec<_>>();

let res = insert_balance_in_chunks(conn, balances)?;
insert_tokens(
conn,
balances
.iter()
.map(|balance| balance.token.clone())
.collect::<Vec<_>>(),
)?;

seed_tokens_from_balance(conn, balances.clone())?;

let res = insert_balance_in_chunks(conn, balances);

assert_eq!(res, ());
assert!(res.is_ok());

anyhow::Ok(())
})
.await
.expect("Failed to run test");
}

fn seed_tokens_from_balance(
conn: &mut PgConnection,
balance: Vec<Balance>,
) -> anyhow::Result<()> {
insert_tokens(
conn,
balance
.iter()
.map(|balance| balance.token.clone())
.collect::<Vec<_>>(),
)?;

anyhow::Ok(())
}

fn seed_balance(
conn: &mut PgConnection,
balances: Vec<Balance>,
) -> anyhow::Result<()> {
seed_tokens_from_balance(conn, balances.clone())?;

diesel::insert_into(balances::table)
.values::<&Vec<BalancesInsertDb>>(
&balances
Expand All @@ -391,13 +463,18 @@ mod tests {
fn query_balance_by_address(
conn: &mut PgConnection,
owner: Id,
token: Id,
token: Token,
) -> anyhow::Result<BalanceDb> {
let token = match token {
Token::Native(token) => token.to_string(),
Token::Ibc(token) => token.address.to_string(),
};

balances::table
.filter(
balances::dsl::owner
.eq(owner.to_string())
.and(balances::dsl::token.eq(token.to_string())),
.and(balances::dsl::token.eq(token)),
)
.select(BalanceDb::as_select())
.first(conn)
Expand Down
Loading
Loading