Skip to content

Commit

Permalink
remove txns
Browse files Browse the repository at this point in the history
  • Loading branch information
Tguntenaar committed Dec 23, 2024
1 parent 58fdaa3 commit 9e5df66
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 172 deletions.
28 changes: 0 additions & 28 deletions migrations/20241217195849_sputnik.sql
Original file line number Diff line number Diff line change
Expand Up @@ -29,34 +29,6 @@ CREATE INDEX idx_dao_proposals_total_votes ON dao_proposals (total_votes);
CREATE INDEX idx_dao_proposals_dao_instance ON dao_proposals (dao_instance);
CREATE INDEX idx_dao_proposals_proposal_action ON dao_proposals (proposal_action);

CREATE TABLE IF NOT EXISTS
txns (
id SERIAL PRIMARY KEY,
tx_id BIGINT NOT NULL,
hash VARCHAR NOT NULL,
author_id VARCHAR NOT NULL,
dao_instance VARCHAR NOT NULL,
proposer VARCHAR NOT NULL,
description VARCHAR NOT NULL,
kind VARCHAR NOT NULL,
status VARCHAR NOT NULL,
total_votes INT NOT NULL,
vote_counts JSONB NOT NULL,
votes JSONB NOT NULL,
submission_time BIGINT NOT NULL,
proposal_action VARCHAR NOT NULL
);

CREATE INDEX idx_txns_hash ON txns (hash);
CREATE INDEX idx_txns_author_id ON txns (author_id);
CREATE INDEX idx_txns_dao_instance ON txns (dao_instance);
CREATE INDEX idx_txns_proposer ON txns (proposer);
CREATE INDEX idx_txns_description ON txns (description);
CREATE INDEX idx_txns_kind ON txns (kind);
CREATE INDEX idx_txns_status ON txns (status);
CREATE INDEX idx_txns_submission_time ON txns (submission_time);
CREATE INDEX idx_txns_proposal_action ON txns (proposal_action);

CREATE TABLE IF NOT EXISTS
dao_instances_last_updated_info (
instance VARCHAR NOT NULL PRIMARY KEY,
Expand Down
123 changes: 3 additions & 120 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::{
entrypoints::{
proposal::proposal_types::GetProposalFilters,
rfp::rfp_types::GetRfpFilters,
sputnik::{GetDaoProposalsFilters, GetTxnsFilters},
proposal::proposal_types::GetProposalFilters, rfp::rfp_types::GetRfpFilters,
sputnik::GetDaoProposalsFilters,
},
timestamp_to_date_string,
};
Expand All @@ -22,7 +21,7 @@ pub mod db_types;

use db_types::{
BlockHeight, LastUpdatedInfo, ProposalSnapshotRecord, ProposalWithLatestSnapshotView,
RfpSnapshotRecord, RfpWithLatestSnapshotView, SputnikProposalSnapshotRecord, SputnikTxnsRecord,
RfpSnapshotRecord, RfpWithLatestSnapshotView, SputnikProposalSnapshotRecord,
};

impl DB {
Expand Down Expand Up @@ -948,62 +947,6 @@ impl DB {
}
}

pub async fn insert_txn(
tx: &mut Transaction<'static, Postgres>,
record: SputnikTxnsRecord,
) -> anyhow::Result<()> {
let sql = r#"
INSERT INTO txns (id, hash, author_id, dao_instance, proposer, description, kind, status, total_votes, vote_counts, votes, submission_time, proposal_action)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
"#;
let result = sqlx::query(sql)
.bind(record.id)
.bind(record.hash)
.bind(record.author_id)
.bind(&record.dao_instance)
.bind(record.proposer)
.bind(record.description)
.bind(record.kind)
.bind(record.status)
.bind(record.total_votes)
.bind(record.vote_counts)
.bind(record.votes)
.bind(record.submission_time)
.bind(record.proposal_action)
.execute(tx.as_mut())
.await;

match result {
Ok(_) => {
println!(
"Inserted transaction from account {} and id {:?}",
&record.dao_instance, record.id
);
Ok(())
}
Err(e) => {
eprintln!("Failed to insert txn: {:?}", e);
Err(anyhow::anyhow!("Failed to insert txn"))
}
}
}

// pub async fn get_proposal_by_id(
// &self,
// proposal_id: i64,
// ) -> Result<Option<ProposalRecord>, sqlx::Error> {
// let sql = r#"
// SELECT *
// FROM proposals
// WHERE id = $1
// "#;
// let proposal = sqlx::query_as::<_, ProposalRecord>(sql)
// .bind(proposal_id)
// .fetch_optional(&self.0)
// .await?;
// Ok(proposal)
// }

pub async fn get_dao_proposals(
&self,
dao_instance: &str,
Expand Down Expand Up @@ -1067,66 +1010,6 @@ impl DB {

Ok((proposals, total_count))
}

pub async fn get_txns(
&self,
account_id: &str,
limit: i64,
order: &str,
offset: i64,
filters: Option<GetTxnsFilters>,
) -> anyhow::Result<(Vec<SputnikTxnsRecord>, i64)> {
// Validate the order clause to prevent SQL injection
let order_clause = match order.to_lowercase().as_str() {
"ts_asc" => "submission_time ASC",
"ts_desc" => "submission_time DESC",
"id_asc" => "id ASC",
"id_desc" => "id DESC",
_ => "id DESC", // Default to DESC if the order is not recognized
};

let author_id = filters.as_ref().and_then(|f| f.author_id.as_ref());
let kind = filters.as_ref().and_then(|f| f.kind.as_ref());
// let total_votes = filters.as_ref().and_then(|f| f.total_votes.as_ref());
let status = filters.as_ref().and_then(|f| f.status.as_ref());

let sql = format!(
r#"
SELECT *
FROM txns
WHERE dao_instance = $1
AND ($2 IS NULL OR author_id = $2)
AND ($3 IS NULL OR kind = $3)
AND ($4 IS NULL OR status = $4)
ORDER BY {}
LIMIT $5 OFFSET $6
"#,
order_clause,
);

let txns = sqlx::query_as::<_, SputnikTxnsRecord>(&sql)
.bind(account_id)
.bind(author_id)
.bind(kind)
.bind(status)
.bind(limit)
.bind(offset)
.fetch_all(&self.0)
.await?;

let count_sql = r#"
SELECT COUNT(*)
FROM txns
WHERE dao_instance = $1
"#;

let total_count = sqlx::query_scalar::<_, i64>(count_sql)
.bind(account_id)
.fetch_one(&self.0)
.await?;

Ok((txns, total_count))
}
}

async fn run_migrations(rocket: Rocket<Build>) -> fairing::Result {
Expand Down
11 changes: 0 additions & 11 deletions src/entrypoints/sputnik/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,6 @@ pub struct GetDaoProposalsFilters {
pub proposal_action: Option<String>,
}

#[derive(Clone, Debug, FromForm, ToSchema)]
pub struct GetTxnsFilters {
pub author_id: Option<String>,
pub instance: Option<String>,
pub proposer: Option<String>,
pub status: Option<String>,
pub kind: Option<String>,
pub description: Option<String>,
pub proposal_action: Option<String>,
}

async fn fetch_dao_proposals(
db: &DB,
account_id: &str,
Expand Down
22 changes: 12 additions & 10 deletions src/nearblocks_client/sputnik.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ use serde_json::Value;

use super::types::BLOCK_HEIGHT_OFFSET;

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct AddProposalArgs {
pub proposal: ProposalInput,
}

#[derive(Serialize, Deserialize, Clone)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ProposalInput {
pub description: String,
pub kind: ProposalKind,
Expand Down Expand Up @@ -81,13 +81,15 @@ pub async fn handle_add_proposal(
db: &State<DB>,
contract: &AccountId,
) -> Result<(), Status> {
// let action = transaction
// .actions
// .as_ref()
// .and_then(|actions| actions.first())
// .ok_or(Status::InternalServerError)?;
// let json_args = action.args.clone();
// let args: AddProposalArgs = serde_json::from_str(&json_args.unwrap_or_default()).unwrap();
let action = transaction
.actions
.as_ref()
.and_then(|actions| actions.first())
.ok_or(Status::InternalServerError)?;
let json_args = action.args.clone();
let args: AddProposalArgs = serde_json::from_str(&json_args.unwrap_or_default()).unwrap();

println!("Args: {:?}", args);

let rpc_service = RpcService::new(contract);

Expand All @@ -98,7 +100,7 @@ pub async fn handle_add_proposal(
)
.await
{
Ok(last_proposal_id) => last_proposal_id.data,
Ok(last_proposal_id) => last_proposal_id.data - 1, // TODO TEST
Err(e) => {
eprintln!("Failed to get last dao proposal id on block: {:?}", e);
return Err(Status::InternalServerError);
Expand Down
6 changes: 3 additions & 3 deletions src/rpc_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,13 @@ impl RpcService {
Err(on_block_error) => match self.get_dao_proposal(proposal_id).await {
Ok(proposal) => Ok(proposal.data),
Err(rpc_error) => {
eprintln!("Block error {:?}", on_block_error);
eprintln!(
"Failed get_dao_proposal_on_block from RPC on block height {} and id {}",
block_id, proposal_id,
);
eprintln!("{:?}", on_block_error);
eprintln!("{:?}", rpc_error);
// Err(Status::InternalServerError)
eprintln!("RPC error {:?}", rpc_error);

// TODO issue 1018
Ok(ProposalOutput {
id: proposal_id.try_into().unwrap(),
Expand Down

0 comments on commit 9e5df66

Please sign in to comment.